package cn.chainco.cts.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;

import cn.chainco.cts.iservice.CommonManager;
import cn.chainco.cts.iservice.IExcRateManager;
import cn.chainco.cts.iservice.IWorkManager;
import cn.chainco.cts.jdo.Company;
import cn.chainco.cts.jdo.ContainerNo;
import cn.chainco.cts.jdo.Currency;
import cn.chainco.cts.jdo.DocTemplate;
import cn.chainco.cts.jdo.Employee;
import cn.chainco.cts.jdo.ExcRate;
import cn.chainco.cts.jdo.Fee;
import cn.chainco.cts.jdo.Item;
import cn.chainco.cts.jdo.Point;
import cn.chainco.cts.jdo.Tag;
import cn.chainco.cts.jdo.User;
import cn.chainco.cts.jdo.Work;
import cn.chainco.cts.jdo.WorkDoc;
import cn.chainco.cts.jdo.WorkFee;
import cn.chainco.cts.jdo.WorkItem;
import cn.chainco.cts.jdo.WorkTeam;
import cn.chainco.cts.utils.CommUtils;
import cn.chainco.cts.utils.Constants;
import cn.chainco.cts.utils.CookieUtil;
import cn.chainco.cts.utils.TimeUtil;
import cn.chainco.cts.utils.excel.ExcelProperty;
import cn.chainco.cts.utils.excel.ExcelTitle;
import cn.chainco.cts.utils.excel.ExportExcel;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings({ "unchecked", "unused" })
@InterceptorRef("ctsInterceptors")
public class WorkAction extends ActionSupport {
	private static final long serialVersionUID = -2542268427567938781L;
	private IWorkManager workManager;
	private IExcRateManager excRateManager;
	private CommonManager commonManager;
	private Integer itemType=1;
	private int pageSize = 15;
	private int pageNumber = 1;
	private String keyword;
	private Work work;
	private ContainerNo containerNo;
	private File myFile;
	private String contentType;
	private String fileName;
	private String myFileContentType;
	private String myFileFileName;
	public static final int BUFFER_SIZE = 2 * 1024;
	private WorkItem workItem;
	
	private List<String> tagsList;//详情显示的标签

	@Action("addOrEditWork")
	public String addOrEditWork(){
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("employee", ActionUtil.getSelectEmployee());
		String language = CookieUtil.getCookieValue(request, "cts_locale");
		int step = 1;
		try{
			step = Integer.parseInt(request.getParameter("step"));
		}catch(NumberFormatException e){
		}
		String workId = request.getParameter("workId");
		if(!CommUtils.isCorrectInt(workId)){
			step = 1;
		}else{
			work = this.commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
		}
		request.setAttribute("step", step);
		request.setAttribute("isReturn", request.getParameter("isReturn"));
		switch(step){
		case 2:
			workStep2();
			break;
		case 3:
			workStep5();
			break;
		case 4:
			workStep3();
			workStep4();
			break;
		case 5:
			workStep6();
			break;
		case 6:
			workStep7();
			break;
		default:
			workStep1();
			break;
		}
		return "work/addoreditwork";
	}

	// 订单第一步
	@Action("workStep1")
	public void workStep1(){
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			Employee employee = ActionUtil.getSelectEmployee();
			String language = CookieUtil.getCookieValue(request, "cts_locale");
			if("true".equals(request.getParameter("save"))){ // 保存
				if(work.getItem() != null && work.getItem().getId() != 0){ // 委托项目不能为空
					work.setItem(commonManager.findEntityByPK(Item.class, work.getItem().getId()));
				}else{
					work.setItem(null);
				}
				Long result = work.getId();
				if(result == null || result == 0){
					if(employee.getAuth1() != 1){
						ActionUtil.outputData(-2);
						return; //没有权限不能创建
					}
					work.setEmployee(employee);
					work.setCompany(employee.getCompany());
					work.setCreateTime(new Date());
					work.setWorkCode(work.getCompany().getPrefix() + work.getWorkCode());
					if(workManager.validateWorkCode(employee.getCompany(), work.getWorkCode())){ // 验证订单号是否存在
						ActionUtil.outputData(-1);
						return;
					}
					if(work.getClient2() != null && work.getClient2().getId() == 0){
						work.setClient2(null);
					}
					result = commonManager.saveEntity(work);
					if(result > 0){  //创建者
						WorkTeam workTeam = new WorkTeam();
						workTeam.setEmployee(employee);
						workTeam.setWork(work);
						workTeam.setAuth(0);
						commonManager.saveEntity(workTeam);
					}
				}else{
					Work editWork = commonManager.findEntityByPK(Work.class, result);
					Company company = this.commonManager.findEntityByPK(Company.class, editWork.getCompany().getId());
					work.setWorkCode(company.getPrefix() + work.getWorkCode());
					if(!editWork.getWorkCode().equals(work.getWorkCode())){
						if(workManager.validateWorkCode(employee.getCompany(), work.getWorkCode())){ // 验证订单号是否存在
							ActionUtil.outputData(-1);
							return;
						}
						editWork.setWorkCode(work.getWorkCode());
					}
					editWork.setDelegateTime(work.getDelegateTime());
					editWork.setClient1(work.getClient1());
					editWork.setClient2(work.getClient2().getId() == 0 ? null : work.getClient2());
					editWork.setTags(work.getTags());
					commonManager.modifyEntity(editWork);
				}
				ActionUtil.outputData(result);
			}

			// 进入第一步读取相关数据
			String workId = request.getParameter("workId");
			if(CommUtils.isCorrectInt(workId)){
				work = commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
				work.setWorkCode(work.getWorkCode().replaceFirst(work.getCompany().getPrefix(), ""));
			}else{
				work = new Work();
				work.setCompany(employee.getCompany());
				work.setWorkCode(workManager.getNewWorkCode(work.getCompany()));
				String type = request.getParameter("itemId");
				if(CommUtils.isCorrectInt(type) && Integer.parseInt(type) <= 5){
					List<Item> items = commonManager.findByCustomizedSQL(Item.class, "type="+type+" limit 1");
					work.setItem(items.get(0));
					work.getItem().setName(!language.equals("zh_CH") ? work.getItem().getName_en() : work.getItem().getName_zh());
				}else{
					work.setItem(new Item());
					work.getItem().setType(6);
				}
				request.setAttribute("isCreate", 1);
			}
			request.setAttribute("tagList", ActionUtil.getCompanyParam(work.getCompany(), 0, 3, 0, 0));
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	// 订单第二步
	@Action("workStep2")
	public void workStep2(){
		HttpServletRequest request = ServletActionContext.getRequest();
		if("true".equals(request.getParameter("save"))){ // 保存
			Work editWork = commonManager.findEntityByPK(Work.class, work.getId());
			Employee employee = ActionUtil.getEmployeeByLogin(editWork.getCompany());
			if(employee == null){
				ActionUtil.outputData("null");
				return;
			}else if(editWork == null){
				ActionUtil.outputData("null");
				return;
			}else if(editWork.getWorkingStatus() == 5){
				ActionUtil.outputData("status5");
				return;
			}
			if(editWork.getItem() != null &&  editWork.getItem().getType() == 4){  //快递
				editWork.setExpressType(work.getExpressType());
				editWork.setExpressPayment1(work.getExpressPayment1());
				editWork.setExpressQuantity(work.getExpressQuantity());
				editWork.setExpressPackageType(work.getExpressPackageType());
				editWork.setExpressWeight(work.getExpressWeight());
				editWork.setExpressVolume(work.getExpressVolume());
				editWork.setExpressVolumeWeight(work.getExpressVolumeWeight());
				editWork.setExpressValue(work.getExpressValue());
				editWork.setExpressDetail(work.getExpressDetail());
				editWork.setExpressShipper(work.getExpressShipper());
				editWork.setExpressConsignee(work.getExpressConsignee());
			}else{
				editWork.setCargoType(work.getCargoType());
				editWork.setCargoName(work.getCargoName());
				editWork.setCy2cy1(work.getCy2cy1());
				editWork.setPayment1(work.getPayment1());
				editWork.setReleaseCargoType1(work.getReleaseCargoType1());
				editWork.setQuantity(work.getQuantity());
				editWork.setPackageType(work.getPackageType());
				editWork.setGrossWeight(work.getGrossWeight());
				editWork.setVolume(work.getVolume());
				editWork.setCargoValue(work.getCargoValue());
				editWork.setMark(work.getMark());
				editWork.setShipper(work.getShipper());
				editWork.setConsignee(work.getConsignee());
				editWork.setNotifyParty(work.getNotifyParty());
				editWork.setSupplier(work.getSupplier());
			}
			commonManager.modifyEntity(editWork);
			ActionUtil.outputData("ok");
			return;
		}
		//进入第二步读取相关数据
		String workId = request.getParameter("workId");
		if(CommUtils.isCorrectInt(workId)){
			work = commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
			if(work == null){
				return;
			}
			int type = 6;
			if(work.getItem() != null){
				type = work.getItem().getType();
			}else{
				work.setItem(new Item());
				work.getItem().setType(type);
			}
			request.setAttribute("allCargoType", ActionUtil.getCompanyParam(null, type ,5 , 1, 0));
			request.setAttribute("allCy2cy", ActionUtil.getCompanyParam(null, type ,5 , 2, 0));
			request.setAttribute("allPayment", ActionUtil.getCompanyParam(null, type ,5 , 3, 0));
			request.setAttribute("allReleaseCargoType", ActionUtil.getCompanyParam(null, type ,5 , 4, 0));
			request.setAttribute("allPackageType", ActionUtil.getCompanyParam(null, type ,5 , 5, 0));
		}
	}

	// 订单第三步
	@Action("workStep3")
	public void workStep3(){
		HttpServletRequest request = ServletActionContext.getRequest();
		if("true".equals(request.getParameter("save"))){ // 保存
			if(work.getId() != null && work.getId() != 0){
				Work editWork = commonManager.findEntityByPK(Work.class, work.getId());
				if(editWork == null){
					return;
				}
				Employee employee = ActionUtil.getEmployeeByLogin(editWork.getCompany());
				if(employee == null){
					ActionUtil.outputData("null");
					return;
				}else if(editWork == null){
					ActionUtil.outputData("null");
					return;
				}else if(editWork.getWorkingStatus() == 5){
					ActionUtil.outputData("status5");
					return;
				}
				if(work.getPointTP() == null){
					work.setPointTP(new Point());
				}
				if(editWork.getItem() == null || editWork.getItem().getType() > 5){ //其它委托项目
					editWork.setPointORG(work.getPointORG());
				}else if(editWork.getItem().getType() == 4){ //快递
					editWork.setExpressExportCountry(work.getExpressExportCountry());
					editWork.setExpressImportCountry(work.getExpressImportCountry());
					editWork.setExpressAgent1(work.getExpressAgent1());
					editWork.setExpressCarrier(work.getExpressCarrier());
					editWork.setExpressBookingNumber(work.getExpressBookingNumber());
					editWork.setExpressDeliveryRequirements(work.getExpressDeliveryRequirements());
					editWork.setExpressDeliveryFeedback(work.getExpressDeliveryFeedback());
					editWork.setExpressProductService(work.getExpressProductService());
					editWork.setExpressPayment2(work.getExpressPayment2());
					
					Date getTime = TimeUtil.controlTime(request.getParameter("work.expressGetTime"));
					Date putTime = TimeUtil.controlTime(request.getParameter("work.expressPutTime"));
					//出口国信息
					editWork.setExpressAddress1(work.getExpressAddress1());
					editWork.setExpressETD(work.getExpressETD());
					editWork.setExpressGetTime(getTime);
					//进口国信息
					editWork.setExpressAddress2(work.getExpressAddress2());
					editWork.setExpressETA(work.getExpressETA());
					editWork.setExpressPutTime(putTime);
					editWork.setExpressAgent2(work.getExpressAgent2().getId() == 0 ? null : work.getExpressAgent2());
				}else if(editWork.getItem().getType() == 5){
					editWork.setPointORG(work.getPointORG());
					editWork.setPointDES(work.getPointDES());
					editWork.setCarrier(work.getCarrier().getId() == 0 ? null : work.getCarrier());
					editWork.setBookingNumber(work.getBookingNumber());
					editWork.setDeliveryRequirements(work.getDeliveryRequirements());
					editWork.setDeliveryFeedback(work.getDeliveryFeedback());
					editWork.setTruckingCarNumber(work.getTruckingCarNumber());
					editWork.setTruckingDriver(work.getTruckingDriver());
					editWork.setTruckingTel(work.getTruckingTel());
					//出发地信息
					editWork.setTruckingAddress1(work.getTruckingAddress1());
					editWork.setTruckingETD(work.getTruckingETD());
					editWork.setTruckingTime1(work.getTruckingTime1());
					//目的地信息
					editWork.setTruckingAddress2(work.getTruckingAddress2());
					editWork.setTruckingETA(work.getTruckingETA());
					editWork.setTruckingTime2(work.getTruckingTime2());
					editWork.setTruckingAgent(work.getTruckingAgent().getId() == 0 ? null : work.getTruckingAgent());
				}else{
					Date cyClosing1 = TimeUtil.controlTime(request.getParameter("work.cyClosing1"));
					Date cyClosing2 = TimeUtil.controlTime(request.getParameter("work.cyClosing2"));
					editWork.setPointORG(work.getPointORG());
					editWork.setPointPOL(work.getPointPOL());
					editWork.setPointPOD(work.getPointPOD());
					editWork.setPointDES(work.getPointDES());
					editWork.setPointTP(work.getPointTP().getId() == 0 ? null : work.getPointTP());
					editWork.setTranshipType1(work.getTranshipType1().getId() == 0 ? null : work.getTranshipType1());
					editWork.setTranshipType2(work.getTranshipType2().getId() == 0 ? null : work.getTranshipType2());
					editWork.setBookingAgent(work.getBookingAgent());
					editWork.setCarrier(work.getCarrier());
					editWork.setBookingNumber(work.getBookingNumber());
					editWork.setBlNumber(work.getBlNumber());
					editWork.setDeliveryRequirements(work.getDeliveryRequirements());
					editWork.setDeliveryFeedback(work.getDeliveryFeedback());
					editWork.setCy2cy2(work.getCy2cy2());
					editWork.setPayment2(work.getPayment2());
					editWork.setReleaseCargoType2(work.getReleaseCargoType2());
					//出发地信息
					editWork.setOceanVessel1(work.getOceanVessel1());
					editWork.setVoyNo1(work.getVoyNo1());
					editWork.setCyClosing1(cyClosing1);
					editWork.setEtd1(work.getEtd1());
					editWork.setDepartureTime1(work.getDepartureTime1());
					//装货港信息
					editWork.setOceanVessel2(work.getOceanVessel2());
					editWork.setVoyNo2(work.getVoyNo2());
					editWork.setOceanVessel5(work.getOceanVessel5());
					editWork.setCyClosing2(cyClosing2);
					editWork.setEtd2(work.getEtd2());
					editWork.setDepartureTime2(work.getDepartureTime2());
					//卸货港信息
					editWork.setOceanVessel4(work.getOceanVessel4());
					editWork.setEta1(work.getEta1());
					editWork.setArrivalTime1(work.getArrivalTime1());
					editWork.setReleaseCargoAgent1(work.getReleaseCargoAgent1().getId() == 0 ? null : work.getReleaseCargoAgent1());
					//目的地信息
					editWork.setOceanVessel3(work.getOceanVessel3());
					editWork.setEta2(work.getEta2());
					editWork.setArrivalTime2(work.getArrivalTime2());
					editWork.setReleaseCargoAgent2(work.getReleaseCargoAgent2().getId() == 0 ? null : work.getReleaseCargoAgent2());
				}
				saveAllWorkItem(); //保存全部作业项目
				commonManager.modifyEntity(editWork);
				workManager.updateWorkStatus(editWork);
				ActionUtil.outputData("ok");
				return;
			}
		}
		
		//进入第三步读取相关数据
		String workId = request.getParameter("workId");
		if(CommUtils.isCorrectInt(workId)){
			work = commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
			if(work == null){
				return;
			}
		}
		int type = 6;
		if(work.getItem() != null){
			type = work.getItem().getType();
		}else{
			work.setItem(new Item());
			work.getItem().setType(type);
		}
		request.setAttribute("allCargoType", ActionUtil.getCompanyParam(null, type ,5 , 1, 0));
		request.setAttribute("allCy2cy", ActionUtil.getCompanyParam(null, type ,5 , 2, 0));
		request.setAttribute("allPayment", ActionUtil.getCompanyParam(null, type ,5 , 3, 0));
		request.setAttribute("allReleaseCargoType", ActionUtil.getCompanyParam(null, type ,5 , 4, 0));
		request.setAttribute("allPackageType", ActionUtil.getCompanyParam(null, type ,5 , 5, 0));
		request.setAttribute("allTranshipType", ActionUtil.getCompanyParam(null, type ,5 , 6, 0));
		request.setAttribute("allCarrier", ActionUtil.getCompanyParam(null, type ,5 , 7, 0));
	}
	//显示箱量
	@Action("showBoxAmount")
	public String showBoxAmount(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String workId = request.getParameter("workId");
		if(CommUtils.isCorrectInt(workId)){
			work = commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
			if(work == null){
				return "";
			}
		}
		request.setAttribute("box", ActionUtil.getBox());
		request.setAttribute("boxTxt", ActionUtil.boxTxt);
		request.setAttribute("boxTypeCount", workManager.getBoxTypeCount(work));
		request.setAttribute("cnList", workManager.getAllContainerNoByWork(work));
		return "work/boxAmount";
	}
	//添加箱量
	@Action("addBoxAmount")
	public String addBoxAmount(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String workId = request.getParameter("workId");
		if(CommUtils.isCorrectInt(workId)){
			work = commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
			if(work == null){
				return showBoxAmount();
			}
		}
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		String[] box = ActionUtil.getBox();
		for (int i = 0; i < box.length; i++) {
			String count = request.getParameter(box[i]);
			if(count != null && CommUtils.isCorrectInt(count)){
				map.put(i, Integer.parseInt(count));
			}else{
				map.put(i, 0);
			}
		}
		if(map.size() > 0){
			request.setAttribute("resultCount", workManager.addBoxAmount(map, work));
			
			StringBuffer boxAmount = new StringBuffer();;
			map = workManager.getBoxTypeCount(work);
			for (Integer key : map.keySet()) {
				boxAmount.append(map.get(key) + "x" + ActionUtil.boxTxt[key] + ",");  //1x20'GP,1x40'GP......
			}
			if(boxAmount.length() > 0){
				boxAmount = new StringBuffer(boxAmount.substring(0, boxAmount.length() - 1));
			}
			work.setBoxAmount(boxAmount.toString());
			commonManager.modifyEntity(work);
		}
		return showBoxAmount();
	}
	//保存柜号
	@Action("saveBoxAmount")
	public void saveBoxAmount(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String workId = request.getParameter("workId");
		if(CommUtils.isCorrectInt(workId)){
			work = commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
			if(work == null){
				return;
			}
		}
		if(containerNo != null && containerNo.getId() != 0){
			ContainerNo cn = commonManager.findEntityByPK(ContainerNo.class, containerNo.getId());
			if(cn != null){
				cn.setCntrNo(containerNo.getCntrNo());
				cn.setSealNo(containerNo.getSealNo());
				cn.setCount(containerNo.getCount());
				cn.setGrossWeight(containerNo.getGrossWeight());
				cn.setVolume(containerNo.getVolume());
				cn.setHasAirintake(containerNo.getHasAirintake());
				cn.setHasDynamo(containerNo.getHasDynamo());
				cn.setTemperature(containerNo.getTemperature());
				cn.setDescription(containerNo.getDescription());
				cn.setHumidity(containerNo.getHumidity());
				commonManager.modifyEntity(cn);
				ActionUtil.outputData("ok");
			}
		}
	}
	//删除柜号
	@Action("delBoxAmount")
	public void delBoxAmount(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String cnId = request.getParameter("cnId");
		if(CommUtils.isCorrectInt(cnId)){
			containerNo = commonManager.findEntityByPK(ContainerNo.class, Long.parseLong(cnId));
			if(containerNo != null){
				work = containerNo.getWork();
				Employee employee = ActionUtil.getEmployeeByLogin(work.getCompany());
				//TODO 权限控制
				commonManager.deleteEntity(containerNo);
				Map<Integer,Integer> map = workManager.getBoxTypeCount(work);
				StringBuffer boxAmount = new StringBuffer();;
				for (Integer key : map.keySet()) {
					boxAmount.append(map.get(key) + "x" + ActionUtil.boxTxt[key] + ",");  //1x20'GP,1x40'GP......
				}
				if(boxAmount.length() > 0){
					boxAmount = new StringBuffer(boxAmount.substring(0, boxAmount.length() - 1));
				}
				work.setBoxAmount(boxAmount.toString());
				commonManager.modifyEntity(work);
				ActionUtil.outputData(work.getBoxAmount() + "ok");
			}
		}
		
	}

	// 订单第四步
	@Action("workStep4")
	public String workStep4(){
		HttpServletRequest request = ServletActionContext.getRequest();
		if(work != null){
			//如果第三步还没完成先完成第三步

//			if((work.getItem().getType() < 4 && (work.getPointORG() == null || work.getPointDES() == null || work.getPointPOL() == null || work.getPointPOD() == null)) ||
//					(work.getItem().getType() == 4 && (work.getExpressExportCountry() == null || work.getExpressImportCountry() == null)) ||
//					(work.getItem().getType() == 5 && (work.getPointORG() == null || work.getPointDES() == null)) || 
//					(work.getItem().getType() > 5 && work.getPointORG() == null)){
//				request.setAttribute("step", "3");
//				request.setAttribute("tips", "1");
//				workStep3();
//				return;
//			}else if(work.getItem().getType() > 5 && work.getPointORG() == null){
//				request.setAttribute("step", "3");
//				workStep2();
//				return;
//			}
			List<WorkItem> allWorkItem = workManager.getWorkItemByType(work, null);
//			workItem = new WorkItem();
//			workItem.setType(null);
//			allWorkItem.add(0, workItem);
			request.setAttribute("allWorkItem", allWorkItem);
			request.setAttribute("allItem", ActionUtil.getCompanyParam(work.getCompany(), null, 1, 2, 0));
		}
		String workFeeId = request.getParameter("workFeeId");
		String fees = request.getParameter("fees");
		String employee1Id = request.getParameter("employee1Id");
		if(CommUtils.isCorrectInt(workFeeId) && CommUtils.isCorrectInt(fees) && CommUtils.isCorrectInt(employee1Id)){
			WorkFee workFee = this.commonManager.findEntityByPK(WorkFee.class, Long.parseLong(workFeeId));
			work = workFee.getWork();
			if(workFee != null){
				List<WorkItem> allWorkItem = new ArrayList<WorkItem>();
				WorkItem _workItem = new WorkItem();
				if(workFee.getWorkItem() != null){
					_workItem.setId(workFee.getWorkItem().getId());
				}else{
					_workItem.setId(0L);
				}
				_workItem.setService(this.commonManager.findEntityByPK(Employee.class, Long.parseLong(employee1Id)));
				_workItem.setItem(this.commonManager.findEntityByPK(Fee.class, Long.parseLong(fees)).getItem());
				allWorkItem.add(_workItem);
				request.setAttribute("allWorkItem", allWorkItem);
				request.setAttribute("editByFee", "1");
				request.setAttribute("workFeeId", workFeeId);
				request.setAttribute("fees", fees);
				request.setAttribute("employee1Id", employee1Id);
				
				request.setAttribute("index", request.getParameter("index"));
				request.setAttribute("tabindex", request.getParameter("tabindex"));
			}
			return "work/workstep4";
		}
		return null;
	}

	// 保存第四步其它委托项目
	@Action("saveWorkItem")
	public void saveWorkItem(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String workId = request.getParameter("workId");
		if(CommUtils.isCorrectInt(workId)){
			work = commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
			if(work == null){
				return;
			}
		}
		if(workItem != null){
			long result = 0;
			String startTime = request.getParameter("startTime");
			String endTime = request.getParameter("endTime");
			try{
				startTime = TimeUtil.getYear(new Date()) + "-" + startTime.replace("/", "-");
				endTime = TimeUtil.getYear(new Date()) + "-" + endTime.replace("/", "-");
				workItem.setStartTime(TimeUtil.controlTime(startTime));
				workItem.setEndTime(TimeUtil.controlTime(endTime));
			}catch (Exception e) {
				return;
			}
			if(workItem.getId() != null &&  workItem.getId() != 0){
				WorkItem editWorkItem = commonManager.findEntityByPK(WorkItem.class, workItem.getId());
				editWorkItem.setItem(workItem.getItem());
				editWorkItem.setService(workItem.getService());
				editWorkItem.setStartTime(workItem.getStartTime());
				editWorkItem.setEndTime(workItem.getEndTime());
				editWorkItem.setServiceRequest(workItem.getServiceRequest());
				editWorkItem.setServiceFeedback(workItem.getServiceFeedback());
				editWorkItem.setStatus(workItem.getStatus());
				commonManager.modifyEntity(editWorkItem);
				result = editWorkItem.getId();
			}else{
				workItem.setWork(work);
				result = commonManager.saveEntity(workItem);
			}
			workManager.updateWorkStatus(work);
			ActionUtil.outputData(result);
		}
	}
	//保存全部作业项目
	public void saveAllWorkItem(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String itemCountStr = request.getParameter("itemCount");
		if(CommUtils.isCorrectInt(itemCountStr)){
			int itemCount = Integer.parseInt(itemCountStr);
			for(int i=0; i<itemCount; i++){
				String workItemIdStr = request.getParameter("workItemId" + i);
				if(CommUtils.isCorrectInt(workItemIdStr)){
					WorkItem workItem = commonManager.findEntityByPK(WorkItem.class, Long.parseLong(workItemIdStr));
					if(workItem == null){
						continue;
					}
//					String itemIdStr = request.getParameter("itemId" + i);
//					String serviceIdStr = request.getParameter("serviceId" + i);
					String typeStr = request.getParameter("type" + i);
					String startTimeStr = request.getParameter("startTime" + i);
					String endTimeStr = request.getParameter("endTime" + i);
					String serviceRequestStr = request.getParameter("serviceRequest" + i);
					String serviceFeedbackStr = request.getParameter("serviceFeedback" + i);
					String statusStr = request.getParameter("status" + i);
//					workItem.setItem(commonManager.findEntityByPK(Item.class, Long.parseLong(itemIdStr)));
//					workItem.setService(commonManager.findEntityByPK(Employee.class, Long.parseLong(serviceIdStr)));
					workItem.setType(Integer.parseInt(typeStr));
					startTimeStr = TimeUtil.getYear(new Date()) + "-" + startTimeStr.replace("/", "-");
					endTimeStr = TimeUtil.getYear(new Date()) + "-" + endTimeStr.replace("/", "-");
					workItem.setStartTime(TimeUtil.controlTime(startTimeStr));
					workItem.setEndTime(TimeUtil.controlTime(endTimeStr));
					workItem.setServiceRequest(serviceRequestStr);
					workItem.setServiceFeedback(serviceFeedbackStr);
					if(CommUtils.isCorrectInt(statusStr)){
						workItem.setStatus(Integer.parseInt(statusStr));
					}else{
						workItem.setStatus(0);
					}
					commonManager.modifyEntity(workItem);
				}
			}
		}
	}
	
	// 删除第四步其它委托项目
	//@Action("delWorkItem")
	public void delWorkItem(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String workItemId = request.getParameter("workItemId");
		if(CommUtils.isCorrectInt(workItemId)){
			workItem = commonManager.findEntityByPK(WorkItem.class, Long.parseLong(workItemId));
			if(workItem != null){
				List<WorkFee> fees = this.commonManager.findByCustomizedSQL(WorkFee.class, " type = 1 and workItemId = " + workItem.getId());
				if(fees != null && fees.size() > 0){
					ActionUtil.outputData("error");
				}else{
					commonManager.deleteEntity(workItem);
					ActionUtil.outputData("ok");
				}
			}
		}
	}

	/**
	 * 第五步：费用
	 */
	@Action("workStep5")
	public void workStep5(){
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			if("true".equals(request.getParameter("save"))){ // 保存
				String op = request.getParameter("op");
				if("save".equals(op)){
					String index = request.getParameter("index");
					if(CommUtils.isCorrectInt(index)){
						WorkFee workFee = null;
						String workFeeId = request.getParameter("workFeeId_" + index);
						String money = request.getParameter("money_" + index);
						if(CommUtils.isCorrectInt(workFeeId)){
							workFee = this.commonManager.findEntityByPK(WorkFee.class, Long.parseLong(workFeeId));
						}else{
							workFee = new WorkFee();
							String workId = request.getParameter("workId");
							workFee.setWork(this.commonManager.findEntityByPK(Work.class, Long.parseLong(workId)));
							if(CommUtils.isCorrectNumber(money)){
								workFee.setNotWrittenOffmoney(Float.parseFloat(money));
							}
						}
						if(CommUtils.isCorrectNumber(money)){
							workFee.setMoney(Float.parseFloat(money));
						}
						String employee1Id = request.getParameter("employee1Id_" + index);
						if(CommUtils.isCorrectInt(employee1Id)){
							workFee.setEmployee1(this.commonManager.findEntityByPK(Employee.class, Long.parseLong(employee1Id)));
						}
						String type = request.getParameter("type_" + index);
						workFee.setType(Integer.parseInt(type));
						String fees = request.getParameter("fees_" + index);
						if(CommUtils.isCorrectInt(fees)){
							workFee.setFee(this.commonManager.findEntityByPK(Fee.class, Long.parseLong(fees)));
						}
						String currency = request.getParameter("currency_" + index);
						if(CommUtils.isCorrectInt(currency)){
							workFee.setCurrency(this.commonManager.findEntityByPK(Currency.class, Long.parseLong(currency)));
						}
						String quantity = request.getParameter("quantity_" + index);
						if(CommUtils.isCorrectNumber(quantity)){
							workFee.setQuantity(Float.parseFloat(quantity));
						}
						String unitPrice = request.getParameter("unitPrice_" + index);
						if(CommUtils.isCorrectNumber(unitPrice)){
							workFee.setUnitPrice(Float.parseFloat(unitPrice));
						}
						String employee2Id = request.getParameter("employee2Id_" + index);
						if(CommUtils.isCorrectInt(employee2Id)){
							workFee.setEmployee2(this.commonManager.findEntityByPK(Employee.class, Long.parseLong(employee2Id)));
						}else{
							workFee.setEmployee2(null);
						}
						String quotaReward = request.getParameter("quotaReward_" + index);
						if(CommUtils.isCorrectNumber(quotaReward)){
							workFee.setQuotaReward(Float.parseFloat(quotaReward));
						}else{
							workFee.setQuotaReward(null);
						}
						String ratioReward = request.getParameter("ratioReward_" + index);
						if(CommUtils.isValidStr(ratioReward) && ratioReward.charAt(ratioReward.length() - 1) == '%'
							&& CommUtils.isCorrectNumber(ratioReward.substring(0, ratioReward.length() - 1))){
							workFee.setRatioReward(Float.parseFloat(ratioReward.substring(0, ratioReward.length() - 1)));
						}else{
							workFee.setRatioReward(null);
						}

						String remark = request.getParameter("remark_" + index);
						workFee.setRemark(remark);

						if(workFee.getType() == 1){ //应付
							if(workFee.getId() == null || workFee.getId() == 0){
								if(workFee.getFee().getItem() != null){
									WorkItem workItem = new WorkItem();
									workItem.setWork(workFee.getWork());
									workItem.setItem(workFee.getFee().getItem());
									workItem.setService(workFee.getEmployee1());
									
									this.commonManager.saveEntity(workItem);
									workFee.setWorkItem(workItem);
								}
							}else{
								String srcHasItem = request.getParameter("srcHasItem");
								String hasItem = request.getParameter("hasItem");
								if("1".equals(srcHasItem) && "".equals(hasItem)){
									if(workFee.getWorkItem() != null){
										this.commonManager.deleteEntity(workFee.getWorkItem());
										workFee.setWorkItem(null);
									}
								}else if("".equals(srcHasItem) && "1".equals(hasItem)){
									WorkItem workItem = new WorkItem();
									workItem.setWork(workFee.getWork());
									workItem.setItem(workFee.getFee().getItem());
									workItem.setService(workFee.getEmployee1());
									
									this.commonManager.saveEntity(workItem);
									workFee.setWorkItem(workItem);
								}else if("".equals(srcHasItem) && "".equals(hasItem)){
									
								}else if("1".equals(srcHasItem) && "1".equals(hasItem)){
									WorkItem workItem = workFee.getWorkItem();
									workItem.setItem(workFee.getFee().getItem());
									workItem.setService(workFee.getEmployee1());
									this.commonManager.modifyEntity(workItem);
								}
							}
						}
						if(workFee.getId() == null || workFee.getId() == 0){
							this.commonManager.saveEntity(workFee);
						}else{
							this.commonManager.modifyEntity(workFee);
						}
						this.workManager.updateWorkFeesStatus(workFee.getWork().getId());
						ActionUtil.outputData(workFee.getId());
					}
				}else if("delete".equals(op)){
					String workFeeId = request.getParameter("workFeeId");
					if(CommUtils.isCorrectInt(workFeeId)){
						WorkFee workFee = this.commonManager.findEntityByPK(WorkFee.class, Long.parseLong(workFeeId));
						long workId = workFee.getWork().getId();
						if(workFee != null){
							if(workFee.getType() == 1 && workFee.getWorkItem() != null){
								this.commonManager.deleteEntity(workFee.getWorkItem());
							}
							this.commonManager.deleteEntity(workFee);
							this.workManager.updateWorkFeesStatus(workId);
							ActionUtil.outputData(1);
						}
					}
					
				}
			}else{
				work = this.commonManager.findEntityByPK(Work.class, Long.parseLong(request.getParameter("workId")));
				Employee employee = ActionUtil.getSelectEmployee();
				List<Fee> fees = ActionUtil.getCompanyParam(employee.getCompany(), 0, 2, 0, null);
				request.setAttribute("fees", fees);

				List<Currency> currencys = ActionUtil.getCompanyParam(employee.getCompany(), 0, 0, 0, null);
				request.setAttribute("currencys", currencys);

				List<WorkFee> workFees = this.commonManager.findByCustomizedSQL(WorkFee.class, " workId = " + work.getId());
				List<WorkFee> workFees1 = new ArrayList<WorkFee>();
				List<WorkFee> workFees2 = new ArrayList<WorkFee>();
				List<WorkFee> workFees3 = new ArrayList<WorkFee>();
				for(WorkFee fee: workFees){
					if(fee.getType() == 0){
						workFees1.add(fee);
					}else if(fee.getType() == 1){
						workFees2.add(fee);
					}else{
						workFees3.add(fee);
					}
				}
				request.setAttribute("workFees1", workFees1);
				request.setAttribute("workFees2", workFees2);
				request.setAttribute("workFees3", workFees3);

				Map<Currency, Float> map = this.excRateManager.getAllCurrencyToRMB();
				StringBuilder sb = new StringBuilder();
				for(Map.Entry<Currency, Float> entry: map.entrySet()){
					sb.append(entry.getKey().getId() + "," + entry.getValue() + ";");
				}
				request.setAttribute("allCurrencyToRMB", CommUtils.deleteLastChar(sb.toString()));
				request.setAttribute("employee", employee);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 修改应付款弹出的保存作业项目
	 */
	@Action("saveWorkItemByFee")
	public void saveWorkItemByFee(){
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			String workItemId = request.getParameter("workItemId" + "0");
			String itemId = request.getParameter("itemId" + "0");
			String serviceId = request.getParameter("serviceId" + "0");
			String type = request.getParameter("type" + "0");
			String startTime = request.getParameter("startTime" + "0");
			startTime = TimeUtil.getYear(new Date()) + "-" + startTime.replace("/", "-");
			String endTime = request.getParameter("endTime" + "0");
			endTime = TimeUtil.getYear(new Date()) + "-" + endTime.replace("/", "-");
			String serviceRequest = request.getParameter("serviceRequest" + "0");
			String serviceFeedback = request.getParameter("serviceFeedback" + "0");
			String status = request.getParameter("status" + "0");
			
			WorkItem workItem = null;
			
			if(!"0".equals(workItemId)){
				workItem = this.commonManager.findEntityByPK(WorkItem.class, Long.parseLong(workItemId));
			}else{
				workItem = new WorkItem();
			}
			if(workItem != null){
				workItem.setItem(this.commonManager.findEntityByPK(Item.class, Long.parseLong(itemId)));
				workItem.setService(this.commonManager.findEntityByPK(Employee.class, Long.parseLong(serviceId)));
				workItem.setType(Integer.parseInt(type));
				workItem.setStartTime(TimeUtil.controlTime(startTime));
				workItem.setEndTime(TimeUtil.controlTime(endTime));
				workItem.setServiceRequest(serviceRequest);
				workItem.setServiceFeedback(serviceFeedback);
				workItem.setStatus("1".equals(status) ? 1 : 0);
				
				if(workItem.getId() == null || workItem.getId() == 0){
					String workFeeId = request.getParameter("workFeeId");
					WorkFee workFee = this.commonManager.findEntityByPK(WorkFee.class, Long.parseLong(workFeeId));
					workItem.setWork(workFee.getWork());
					this.commonManager.saveEntity(workItem);
					
					workFee.setWorkItem(workItem);
					this.commonManager.modifyEntity(workFee);
				}else{
					this.commonManager.modifyEntity(workItem);
				}
				
				String fees = request.getParameter("fees");
				ActionUtil.outputData(fees);
			}
		}catch(NumberFormatException e){
			e.printStackTrace();
			ActionUtil.outputData("");
		}
	}

	/**
	 * 应付费用，打开订单所有的其它委托项目
	 */
	@Action("selectItems")
	public String selectItems(){
		HttpServletRequest request = ServletActionContext.getRequest();
		work = this.commonManager.findEntityByPK(Work.class, Long.parseLong(request.getParameter("workId")));

		List<WorkItem> workItems = this.commonManager.findByCustomizedSQL(WorkItem.class, " workId = " + work.getId() + " ");
		request.setAttribute("workItems", workItems);
		return "work/selectitems";
	}

	/**
	 * 其它委托项目所关联的费用
	 */
	@Action("getFeeInItem")
	public void getFeeInItem(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String ids = "";
		try{
			Item item = this.commonManager.findEntityByPK(Item.class, Long.parseLong(request.getParameter("itemId")));
			if(item != null){
				String fees = item.getFees();
				if(CommUtils.isValidStr(fees)){
					String temp = "(";
					if(fees.charAt(0) == ','){
						fees = fees.substring(1);
					}
					if(fees.charAt(fees.length() - 1) == ','){
						fees = fees.substring(0, fees.length() - 1);
					}
					temp += fees + ")";
					List<Fee> feeList = this.commonManager.findByCustomizedSQL(Fee.class, " id in " + temp);
					for(Fee fee: feeList){
						ids += fee.getId() + ",";
					}
				}
			}
		}catch(Exception e){
			ids = "";
		}
		ActionUtil.outputData(CommUtils.deleteLastChar(ids));
	}

	/**
	 * 第六步：团队
	 */
	@Action("workStep6")
	public void workStep6(){
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			if("true".equals(request.getParameter("save"))){ // 保存
				String op = request.getParameter("op");
				if("save".equals(op)){
					String index = request.getParameter("index");
					if(CommUtils.isCorrectInt(index)){
						String auth = request.getParameter("auth_" + index);
						String employeeId = request.getParameter("employeeId_" + index);
						if("author".equals(auth)){
							String workId = request.getParameter("workId");
							Work work = this.commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
							if(work != null){
								work.setEmployee(this.commonManager.findEntityByPK(Employee.class, Long.parseLong(employeeId)));
								this.commonManager.modifyEntity(work);

								List<WorkTeam> workTeams = this.commonManager.findByCustomizedSQL(WorkTeam.class, " workId = " + work.getId() + " and auth = 0 ");
								if(workTeams != null && workTeams.size() > 0){
									WorkTeam author = workTeams.get(0);
									author.setEmployee(work.getEmployee());
									this.commonManager.modifyEntity(author);
								}
								ActionUtil.outputData(work.getId());
							}
						}else{
							WorkTeam workTeam = null;
							String workTeamId = request.getParameter("workTeamId_" + index);
							if(CommUtils.isCorrectInt(workTeamId)){
								workTeam = this.commonManager.findEntityByPK(WorkTeam.class, Long.parseLong(workTeamId));
							}else{
								workTeam = new WorkTeam();
								String workId = request.getParameter("workId");
								workTeam.setWork(this.commonManager.findEntityByPK(Work.class, Long.parseLong(workId)));
							}
							workTeam.setAuth(Integer.parseInt(auth));
							if(CommUtils.isCorrectInt(employeeId)){
								workTeam.setEmployee(this.commonManager.findEntityByPK(Employee.class, Long.parseLong(employeeId)));
							}
							if(workTeam.getId() == null || workTeam.getId() == 0){
								this.commonManager.saveEntity(workTeam);
							}else{
								this.commonManager.modifyEntity(workTeam);
							}
							ActionUtil.outputData(workTeam.getId());
						}
					}
				}else if("delete".equals(op)){
					String workTeamId = request.getParameter("workTeamId");
					if(CommUtils.isCorrectInt(workTeamId)){
						WorkTeam workTeam = this.commonManager.findEntityByPK(WorkTeam.class, Long.parseLong(workTeamId));
						if(workTeam != null){
							this.commonManager.deleteEntity(workTeam);
							ActionUtil.outputData(1);
						}
					}
				}
			}else{
				List<WorkTeam> workTeams = this.commonManager.findByCustomizedSQL(WorkTeam.class, " workId = " + work.getId() + " and auth <> 0 ");
				request.setAttribute("workTeams", workTeams);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 第七步：文件
	 */
	@Action("workStep7")
	public String workStep7(){
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			Employee employee = ActionUtil.getSelectEmployee();
			if("true".equals(request.getParameter("save"))){
				String fileAddType = request.getParameter("fileAddType");
				String workId = request.getParameter("workId");
				work = this.commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
				if(work != null && employee != null && employee.getCompany() != null){
					if("0".equals(fileAddType)){ //模板生成
						WorkDoc workDoc = null;
						WorkDoc newWorkDoc = null;
						WorkDoc parentWorkDoc = null;
						String workDocId = request.getParameter("workDocId");
						if(CommUtils.isCorrectInt(workDocId)){
							workDoc = this.commonManager.findEntityByPK(WorkDoc.class, Long.parseLong(workDocId));
							if(workDoc.getParentId() != null){
								parentWorkDoc = this.commonManager.findEntityByPK(WorkDoc.class, workDoc.getParentId());
							}
							newWorkDoc = new WorkDoc();
							newWorkDoc.setType(0);
							newWorkDoc.setWork(workDoc.getWork());
							newWorkDoc.setEmployee(employee);
							newWorkDoc.setParentId(parentWorkDoc != null ? parentWorkDoc.getId() : workDoc.getId());
							newWorkDoc.setOperateTime(new Date());
							newWorkDoc.setShareUsers(";," + employee.getId() + ",");
						}else{
							workDoc = new WorkDoc();
							workDoc.setType(0);
							workDoc.setWork(work);
							workDoc.setEmployee(employee);
							workDoc.setOperateTime(new Date());
							workDoc.setShareUsers(";," + employee.getId() + ",");
						}
						String docTemplateId = request.getParameter("rdo_doctemplates");
						if(CommUtils.isCorrectInt(docTemplateId)){
							workDoc.setDocTemplate(this.commonManager.findEntityByPK(DocTemplate.class, Long.parseLong(docTemplateId)));
						}
						String workDocName = request.getParameter("workDocName");
						if(CommUtils.isValidStr(workDocName)){
							workDoc.setName(workDocName);
						}
						if(newWorkDoc != null){
							String workDocContent = request.getParameter("workDocContent");
							newWorkDoc.setContent(workDocContent);
							this.commonManager.saveEntity(newWorkDoc);
						}

						String option4 = request.getParameter("option4");
						if((workDoc.getId() == null || workDoc.getId() == 0) || "1".equals(option4)){
							String[] employeeRight = request.getParameterValues("employeeRight");
							if(employeeRight != null){
								String shareUsers = ",";
								for(String string: employeeRight){
									shareUsers += string + ",";
								}
								String srcShareUsers = parentWorkDoc != null ? parentWorkDoc.getShareUsers() : workDoc.getShareUsers();
								if(CommUtils.isValidStr(srcShareUsers)){
									workDoc.setShareUsers(shareUsers + srcShareUsers.substring(srcShareUsers.indexOf(";")));
								}else{
									workDoc.setShareUsers(shareUsers + ";");
								}
							}else{
								String srcShareUsers = parentWorkDoc != null ? parentWorkDoc.getShareUsers() : workDoc.getShareUsers();
								if(CommUtils.isValidStr(srcShareUsers)){
									workDoc.setShareUsers(srcShareUsers.substring(srcShareUsers.indexOf(";"), srcShareUsers.length()));
								}else{
									workDoc.setShareUsers(null);
								}
							}
							if(workDoc.getId() == null || workDoc.getId() == 0){
								this.commonManager.saveEntity(workDoc);
							}else{
								this.commonManager.modifyEntity(workDoc);
							}
						}
						if(parentWorkDoc != null){
							if("1".equals(option4)){
								parentWorkDoc.setShareUsers(workDoc.getShareUsers());
								this.commonManager.modifyEntity(parentWorkDoc);

								if(CommUtils.isValidStr(workDoc.getShareUsers()) && workDoc.getShareUsers().indexOf(";") != -1){
									workDoc.setShareUsers(workDoc.getShareUsers().substring(workDoc.getShareUsers().indexOf(";")));
									this.commonManager.modifyEntity(workDoc);
								}
							}
						}
					}else{//上传文件
						WorkDoc workDoc = null;
						String workDocId = request.getParameter("workDocId");
						if(CommUtils.isCorrectInt(workDocId)){
							workDoc = this.commonManager.findEntityByPK(WorkDoc.class, Long.parseLong(workDocId));
						}else{
							workDoc = new WorkDoc();
							workDoc.setType(1);
							workDoc.setWork(work);
							workDoc.setEmployee(employee);
							workDoc.setOperateTime(new Date());
						}
						String[] employeeRight = request.getParameterValues("employeeRight");
						if(employeeRight != null){
							String shareUsers = ",";
							for(String string: employeeRight){
								shareUsers += string + ",";
							}
							workDoc.setShareUsers(shareUsers);
						}else{
							workDoc.setShareUsers(null);
						}
						if(workDoc.getId() == null || workDoc.getId() == 0){
							this.commonManager.saveEntity(workDoc);
						}else{
							this.commonManager.modifyEntity(workDoc);
						}
						if(CommUtils.isValidStr(myFileFileName) && myFile != null){
							String extention = myFileFileName.substring(myFileFileName.lastIndexOf("."), myFileFileName.length());
							String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
							workDoc.setPath(uuid + extention + ";" + myFileFileName);
							workDoc.setName(myFileFileName);
							this.commonManager.modifyEntity(workDoc);

							InputStream in = null;
							OutputStream out = null;
							try{
								String fileFolder = ServletActionContext.getServletContext().getRealPath(
									File.separator + Constants.BASE_DIR + File.separator + Constants.WORK_FILE + File.separator + employee.getCompany().getId() + File.separator
										+ work.getId());
								File temp = new File(fileFolder);
								if(!temp.isDirectory()){
									temp.mkdirs();
								}
								File dst = new File(fileFolder + File.separator + uuid + extention);
								in = new BufferedInputStream(new FileInputStream(myFile), BUFFER_SIZE);
								out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
								byte[] buffer = new byte[BUFFER_SIZE];
								while(in.read(buffer) > 0){
									out.write(buffer);
								}
							}catch(Exception e){
								e.printStackTrace();
							}finally{
								if(null != in){
									in.close();
								}
								if(null != out){
									out.close();
								}
							}
						}
					}
				}
				request.setAttribute("toUrl", "addOrEditWork?step=6&workId=" + workId);
				return "common/forward";
			}else{
				//文档列表
				List<WorkDoc> workDocs = this.commonManager.findByCustomizedSQL(WorkDoc.class, " parentId is null and workId = " + work.getId());
				List<WorkDoc> workDocs1 = new ArrayList<WorkDoc>();
				List<WorkDoc> workDocs2 = new ArrayList<WorkDoc>();
				for(WorkDoc doc: workDocs){
					if(doc.getType() == 0){
						List<WorkDoc> childDocs = this.commonManager.findByCustomizedSQL(WorkDoc.class, " parentId = " + doc.getId() + " order by operateTime desc ");
						if(childDocs == null || childDocs.size() == 0){
							doc.setOption1(1);
						}else if(childDocs.size() == 1){
							doc.setOption1(2);
						}else{
							doc.setOption1(3);
						}
						if(doc.getEmployee() != null){
							String shareUsers = doc.getShareUsers();
							String readedUser = null;
							if(CommUtils.isValidStr(shareUsers) && shareUsers.indexOf(";") != -1){
								readedUser = shareUsers.substring(shareUsers.indexOf(";") + 1, shareUsers.length());
							}
							if(childDocs == null || childDocs.size() == 0){ // 没有历史记录
								if(!CommUtils.isValidStr(readedUser) || readedUser.indexOf("," + employee.getId() + ",") == -1){
									doc.setOption2(0); // New
								}
							}else{
								int unReadCount = 0;
								if(!CommUtils.isValidStr(readedUser) || readedUser.indexOf("," + employee.getId() + ",") == -1){
									unReadCount++;
								}
								for(WorkDoc childDoc: childDocs){
									String _readedUser = childDoc.getShareUsers(); // 历史记录没有共享用户，保存的已读用户ids
									if(!CommUtils.isValidStr(_readedUser) || _readedUser.indexOf("," + employee.getId() + ",") == -1){
										unReadCount++;
									}
								}
								if(unReadCount > 5){
									unReadCount = 5;
								}
								doc.setOption2(unReadCount == 0 ? null : unReadCount);
							}
						}
						if(childDocs == null || childDocs.size() == 0){
							doc.setOption3(doc.getId() + ""); // 没有历史记录，点击打开自己
						}else{
							doc.setOption3(childDocs.get(0).getId() + ""); // 设置第一次点击时打开最新修改记录
						}
						if(employee.getType() == 2 || employee.getId() == doc.getEmployee().getId()){
							doc.setOption4("1"); // 是管理员或作者，可以删除和编辑和导出
						}else{
							String shareUsers = doc.getShareUsers();
							if(CommUtils.isValidStr(shareUsers) && shareUsers.indexOf(";") != -1){
								String shareUserIds = shareUsers.substring(0, shareUsers.indexOf(";"));
								if(CommUtils.isValidStr(shareUserIds) && shareUserIds.indexOf("," + employee.getId() + ",") != -1){
									doc.setOption4("2"); // 被共享者，可以编辑和导出，共享者不能编辑共享用户
								}
							}
						}
						workDocs1.add(doc);
					}else{
						String path = doc.getPath();
						if(CommUtils.isValidStr(path) && path.indexOf(";") != -1 && path.indexOf(".") != -1){
							String extention = path.substring(path.indexOf(".") + 1, path.indexOf(";"));
							if("doc".equals(extention.toLowerCase()) || "docx".equals(extention.toLowerCase())){
								doc.setOption1(10);
							}else if("jpg".equals(extention.toLowerCase()) || "jpeg".equals(extention.toLowerCase()) || "bmp".equals(extention.toLowerCase())
								|| "gif".equals(extention.toLowerCase()) || "png".equals(extention.toLowerCase())){
								doc.setOption1(11);
							}else if("pdf".equals(extention.toLowerCase())){
								doc.setOption1(12);
							}else if("ppt".equals(extention.toLowerCase()) || "pptx".equals(extention.toLowerCase())){
								doc.setOption1(13);
							}else if("rar".equals(extention.toLowerCase()) || "zip".equals(extention.toLowerCase()) || "7z".equals(extention.toLowerCase())){
								doc.setOption1(14);
							}else if("xls".equals(extention.toLowerCase()) || "xlsx".equals(extention.toLowerCase())){
								doc.setOption1(15);
							}else{
								doc.setOption1(1);
							}
							String filename = path.substring(path.indexOf(";") + 1, path.length());
							doc.setOption3(filename);
						}
						String shareUsers = doc.getShareUsers();
						if(employee.getType() == 2 || employee.getId() == doc.getEmployee().getId()){
							doc.setOption4("1"); // 是管理员或作者，可以下载和删除和编辑
						}else if(CommUtils.isValidStr(shareUsers) && shareUsers.indexOf("," + employee.getId() + ",") != -1){
							doc.setOption4("2"); // 被共享者，可以下载
						}
						workDocs2.add(doc);
					}
				}
				request.setAttribute("workDocs1", workDocs1);
				request.setAttribute("workDocs2", workDocs2);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 文档新增，自定义上传、文档修改弹出的页面
	 */
	@Action("selectDocs")
	public String selectDocs(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String workDocId = request.getParameter("workDocId");
		if(CommUtils.isCorrectInt(workDocId)){
			WorkDoc workDoc = this.commonManager.findEntityByPK(WorkDoc.class, Long.parseLong(workDocId));
			if(workDoc != null){
				List<Employee> employees1 = this.commonManager.findByCustomizedSQL(Employee.class, " companyId = " + workDoc.getEmployee().getCompany().getId() + " and id <> "
					+ workDoc.getEmployee().getId());
				List<Employee> employees2 = new ArrayList<Employee>();
				String shareUsers = workDoc.getShareUsers();
				if(CommUtils.isValidStr(shareUsers)){
					String[] temp = shareUsers.split(",");
					for(String string: temp){
						if(CommUtils.isValidStr(string)){
							Employee _employee = this.commonManager.findEntityByPK(Employee.class, Long.parseLong(string));
							if(_employee != null){
								employees2.add(_employee);
								if(employees1.contains(_employee)){
									employees1.remove(_employee);
								}
							}
						}
					}
				}
				request.setAttribute("isEdit", "1");
				request.setAttribute("workDocId", workDocId);
				request.setAttribute("employees1", employees1);
				request.setAttribute("employees2", employees2);
			}
		}else{
			Employee employee = ActionUtil.getSelectEmployee();
			List<DocTemplate> docTemplates = this.commonManager.findByCustomizedSQL(DocTemplate.class, " companyId = " + employee.getCompany().getId());
			request.setAttribute("docTemplates", docTemplates);

			List<Employee> employees = this.commonManager.findByCustomizedSQL(Employee.class, " companyId = " + employee.getCompany().getId() + " and id <> " + employee.getId());
			List<Employee> employees1 = new ArrayList<Employee>();
			List<Employee> employees2 = new ArrayList<Employee>();
			for(Employee _employee: employees){
				if(_employee.getType() == 1){
					employees1.add(_employee);
				}else{
					employees2.add(_employee);
				}
			}
			request.setAttribute("employees1", employees1);
			request.setAttribute("employees2", employees2);
		}

		String isTeamMember = null; // TODO 是否团队成员，是否只有团队成员才可以用文档生成文件？
		request.setAttribute("isTeamMember", isTeamMember);
		return "work/selectdocs";
	}

	/**
	 * 模板导入类型文档的内容加载
	 */
	@Action("loadWorkDocContent")
	public String loadWorkDocContent(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String workDocId = request.getParameter("workDocId");
		String option4 = request.getParameter("option4");
		String ajaxLoad = request.getParameter("ajaxLoad"); //ajaxLoad == 1为加载由模板生成的文档内容
		if(CommUtils.isCorrectInt(workDocId) && (CommUtils.isValidStr(option4) || "1".equals(ajaxLoad))){
			WorkDoc workDoc = this.commonManager.findEntityByPK(WorkDoc.class, Long.parseLong(workDocId));
			request.setAttribute("workDoc", workDoc);
			WorkDoc parentWorkDoc = null;
			if(workDoc != null){
				String ajaxLoadContent = "";
				Long parentId = workDoc.getParentId();
				if(parentId != null && parentId != 0){
					ajaxLoadContent = workDoc.getContent();
					parentWorkDoc = this.commonManager.findEntityByPK(WorkDoc.class, parentId);
					request.setAttribute("parentWorkDoc", parentWorkDoc);
				}else{
					ajaxLoadContent = workDoc.getDocTemplate() != null ? workDoc.getDocTemplate().getContent() : "";
				}
				if("1".equals(ajaxLoad)){
					request.setAttribute("ajaxLoadContent", ajaxLoadContent);
					request.setAttribute("isHistory", request.getParameter("isHistory")); 
					return "work/doccontent";
				}
				String shareUsers = parentWorkDoc != null ? parentWorkDoc.getShareUsers() : workDoc.getShareUsers();
				if(CommUtils.isValidStr(shareUsers) && shareUsers.indexOf(";") != -1){
					String shareUserIds = shareUsers.substring(0, shareUsers.indexOf(";"));
					if(CommUtils.isValidStr(shareUserIds)){
						String shareUserName = "";
						String[] temp = shareUserIds.split(",");
						for(String string: temp){
							if(CommUtils.isCorrectInt(string)){
								Employee employee = this.commonManager.findEntityByPK(Employee.class, Long.parseLong(string));
								if(employee != null){
									shareUserName += employee.getNickname() + " ";
								}
							}
						}
						request.setAttribute("shareUserName", shareUserName);
					}
				}
			}
			String isEdit = request.getParameter("isEdit");
			if("1".equals(isEdit)){
				if(workDoc.getParentId() != null){
					workDoc = this.commonManager.findEntityByPK(WorkDoc.class, workDoc.getParentId());
				}
				if(workDoc.getEmployee() != null && workDoc.getEmployee().getCompany() != null){
					List<Employee> employees1 = this.commonManager.findByCustomizedSQL(Employee.class, " companyId = " + workDoc.getEmployee().getCompany().getId() + " and id <> "
						+ workDoc.getEmployee().getId());
					List<Employee> employees2 = new ArrayList<Employee>();
					String shareUsers = workDoc.getShareUsers();
					if(CommUtils.isValidStr(shareUsers) && shareUsers.indexOf(";") != -1){
						String[] temp = shareUsers.substring(0, shareUsers.indexOf(";")).split(",");
						for(String string: temp){
							if(CommUtils.isValidStr(string)){
								Employee _employee = this.commonManager.findEntityByPK(Employee.class, Long.parseLong(string));
								if(_employee != null){
									employees2.add(_employee);
									if(employees1.contains(_employee)){
										employees1.remove(_employee);
									}
								}
							}
						}
					}
					request.setAttribute("employees1", employees1);
					request.setAttribute("employees2", employees2);
				}
				request.setAttribute("isEdit", isEdit);
			}
			List<WorkDoc> childDocs = new ArrayList<WorkDoc>();
			Long parentId = workDoc.getParentId();
			if(parentId != null && parentId != 0){
				childDocs = this.commonManager.findByCustomizedSQL(WorkDoc.class, " parentId = " + parentId + " or id = " + parentId + " order by operateTime desc ");
				if(childDocs != null && childDocs.size() > 0){
					WorkDoc theParent = childDocs.get(childDocs.size() - 1);
					for(WorkDoc doc: childDocs){
						doc.setOption4(theParent.getName() + " " + TimeUtil.getMM_DDHHMM(doc.getOperateTime()));
					}
					request.setAttribute("childDocs", childDocs);
				}
			}
		}
		request.setAttribute("option4", option4);
		request.setAttribute("workDocId", workDocId);
		return "work/workdoccontent";
	}

	/**
	 * 下载上传的文件
	 */
	@Action("downloadWorkDoc")
	public void downloadWorkDoc(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		try{
			String workDocId = request.getParameter("workDocId");
			if(CommUtils.isCorrectInt(workDocId)){
				WorkDoc workDoc = this.commonManager.findEntityByPK(WorkDoc.class, Long.parseLong(workDocId));
				if(workDoc != null && workDoc.getWork() != null && workDoc.getEmployee() != null && workDoc.getEmployee().getCompany() != null){
					String path = workDoc.getPath();
					if(CommUtils.isValidStr(path) && path.indexOf(";") != -1 && path.indexOf(".") != -1){
						String fileName = path.substring(0, path.indexOf(";"));
						String filePath = ServletActionContext.getServletContext().getRealPath(
							File.separator + Constants.BASE_DIR + File.separator + Constants.WORK_FILE + File.separator + workDoc.getEmployee().getCompany().getId()
								+ File.separator + workDoc.getWork().getId() + File.separator + fileName);
						File file = new File(filePath);
						if(file != null){
							InputStream fis = new FileInputStream(file);
							byte[] buffer = new byte[fis.available()];
							fis.read(buffer);
							fis.close();
							response.reset();
							response.setContentType("application/x-msdownload;charset=UTF-8");
							response.setCharacterEncoding("UTF-8");
							String _fileName = path.substring(path.indexOf(";") + 1, path.length());
							if("FF".equals(getBrowser(request))){
								//针对火狐浏览器处理
								_fileName = new String(_fileName.getBytes("UTF-8"), "iso-8859-1");
							}else{
								_fileName = URLEncoder.encode(_fileName, "UTF-8");
							}
							response.setHeader("Content-disposition", "attachment;filename=" + _fileName);
							OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
							toClient.write(buffer);
							toClient.flush();
							toClient.close();
						}
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private String getBrowser(HttpServletRequest request){
	    String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
	    if(UserAgent!=null){
	        if (UserAgent.indexOf("msie") >=0 ) return "IE";
	        if (UserAgent.indexOf("firefox") >= 0) return "FF";
	        if (UserAgent.indexOf("safari") >= 0) return "SF";
	    }
	    return null;
	}

	/**
	 * 删除上传的文件，删除硬盘的文件，和所有历史记录
	 */
	@Action("deleteWorkDoc")
	public void deleteWorkDoc(){
		HttpServletRequest request = ServletActionContext.getRequest();
		try{
			String workDocId = request.getParameter("workDocId");
			if(CommUtils.isCorrectInt(workDocId)){
				WorkDoc workDoc = this.commonManager.findEntityByPK(WorkDoc.class, Long.parseLong(workDocId));
				if(workDoc != null){
					if(workDoc.getType() == 1 && workDoc.getWork() != null && workDoc.getEmployee() != null && workDoc.getEmployee().getCompany() != null){
						String path = workDoc.getPath();
						if(CommUtils.isValidStr(path) && path.indexOf(";") != -1 && path.indexOf(".") != -1){
							String fileName = path.substring(0, path.indexOf(";"));
							String filePath = ServletActionContext.getServletContext().getRealPath(
								File.separator + Constants.BASE_DIR + File.separator + Constants.WORK_FILE + File.separator + workDoc.getEmployee().getCompany().getId()
									+ File.separator + workDoc.getWork().getId() + File.separator + fileName);
							File file = new File(filePath);
							if(file != null){
								file.delete();
							}
						}
					}
					if(workDoc.getParentId() != null && workDoc.getParentId() != 0){
						Long parentId = workDoc.getParentId();
						if(parentId != null){
							List<WorkDoc> childDocs = this.commonManager.findByCustomizedSQL(WorkDoc.class, " parentId = " + parentId + " or id = " + parentId);
							for(WorkDoc doc: childDocs){
								this.commonManager.deleteEntity(doc);
							}
						}
					}else{
						this.commonManager.deleteEntity(workDoc);
					}
					ActionUtil.outputData(1);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	


	/**
	 * 订单详情
	 * @return
	 */
	@Action("workDetail")
	public String toWorkDetail(){
		HttpServletRequest request=ServletActionContext.getRequest();	
		List<WorkItem> workItem1=new ArrayList<WorkItem>();
		List<WorkItem> workItem2=new ArrayList<WorkItem>();
		List<WorkItem> workItem3=new ArrayList<WorkItem>();
		List<WorkItem> workItem4=new ArrayList<WorkItem>();
		List<WorkItem> workItem5=new ArrayList<WorkItem>();
		List<WorkItem> workItem6=new ArrayList<WorkItem>();
		String idStr=request.getParameter("id");
		if(idStr==null || "".equals(idStr)){
			idStr="0";
		}
		long workId=Long.parseLong(idStr);
		work=this.commonManager.findEntityByPK(Work.class, workId);
		
		if( work != null){
			List<WorkTeam> workTeamList=this.commonManager.findByCustomizedSQL(WorkTeam.class, " workId = "+work.getId());
			//控制权限
			String cts_employeecpyid = CookieUtil.getCookieValue(request, "cts_employeecpyid");
			String userId = CookieUtil.getCookieValue(request, "cts_userid");
			if(cts_employeecpyid==null || "".equals(cts_employeecpyid)){
				request.setAttribute("msg", "抱歉!您没有权限查看该订单!");
				return "work/noWorkDetail";
			}
			Employee employee=this.commonManager.findEntityByPK(Employee.class, Long.parseLong(cts_employeecpyid));
			//List<Employee> visitedList=this.commonManager.findByCustomizedSQL(Employee.class, " type=1 and companyId="+employee.getCompany().getId());
			List<Employee> visitedList=new ArrayList<Employee>();
			visitedList.add(work.getClient1());
			if(work.getClient2()!=null)visitedList.add(work.getClient2());
			if(work.getReleaseCargoAgent1()!=null)visitedList.add(work.getReleaseCargoAgent1());
			if(work.getReleaseCargoAgent2()!=null)visitedList.add(work.getReleaseCargoAgent2());
			if(work.getBookingAgent()!=null)visitedList.add(work.getBookingAgent());
			if(work.getExpressAgent1()!=null)visitedList.add(work.getExpressAgent1());
			if(work.getExpressAgent2()!=null)visitedList.add(work.getExpressAgent2());
			if(work.getTruckingAgent()!=null)visitedList.add(work.getTruckingAgent());
			
			//如果是访客，但不是自己相关的单没有权限查看
			if(employee!=null && employee.getType()==1){
				if(!visitedList.contains(employee)){
					request.setAttribute("msg", "抱歉!您没有权限查看该订单!");
					return "work/noWorkDetail";
				}
			}else{
				List<Employee> empList=new ArrayList<Employee>();
				for (WorkTeam team : workTeamList) {
					empList.add(team.getEmployee());
				}
				//没有在作业团队里面，或者不是该订单所属公司的管理员都没有权限查看
				if(!empList.contains(employee) && work.getCompany().getUser().getId()!=Long.parseLong(userId)){
					request.setAttribute("msg", "抱歉!您没有权限查看该订单!");
					return "work/noWorkDetail";
				}
			}
			request.setAttribute("workTeamList", workTeamList);//团队
			
			//主航线的ORG到POL的天数
			if(work.getDepartureTime2()!=null && work.getDepartureTime1()!=null){
				int day1=TimeUtil.daysOfTwo(work.getDepartureTime1(),work.getDepartureTime2());
				if(day1==0)day1=1;
				request.setAttribute("day1", day1);
			}
			//主航线的POD到DES的天数
			if(work.getArrivalTime2()!=null && work.getArrivalTime1()!=null){
				int day2=TimeUtil.daysOfTwo(work.getArrivalTime1(),work.getArrivalTime2());
				if(day2==0)day2=1;
				request.setAttribute("day2", day2);
			}
			
			//费用
			List<WorkFee> fees1 = this.workManager.getFeesByWork( work, 0 );// 应收款
			List<WorkFee> fees2 = this.workManager.getFeesByWork( work, 1 );// 应付款
			work.setOption11(fees1);
			work.setOption12(fees2);
			
			List<WorkItem> items = this.workManager.getItemsByWork( work );//其他委托项目
			if( items!=null && items.size()>0 ){
				for( WorkItem obj2: items ){
					if(obj2.getStartTime()!=null && obj2.getEndTime()!=null){
						int day=TimeUtil.daysOfTwo(obj2.getStartTime(), obj2.getEndTime());
						if(day==0)day=1;
						obj2.setOption2(day+"");//设置每个委托项目的天数
						
						if(TimeUtil.toDayIsBetweenDates(obj2.getStartTime(), obj2.getEndTime())){
							obj2.setOption1(2);//任何进行中
						}else if( TimeUtil.dateTimeIsPass(obj2.getEndTime())>=0){
							obj2.setOption1(1);//任务已经完成
						}else{
							obj2.setOption1(0);
						}
					}else{
						obj2.setOption1(0);
					}
					//如果是出发地ORG
					if(obj2.getType()==1){
						//如果是8:短途运输类型的(永远在两侧显示)
//						if(obj2.getItem().getType()==8){
//							workItem1.add(obj2);
//						}else{
							workItem2.add(obj2);
//						}
					}else if(obj2.getType()==2){ //如果是出发港POL
//						if(obj2.getItem().getType()==8){
//							workItem1.add(obj2);
//						}else{
							workItem3.add(obj2);
//						}
					}else if(obj2.getType()==3){ //如果是到达港POD
//						if(obj2.getItem().getType()==8){
//							workItem6.add(obj2);
//						}else{
							workItem4.add(obj2);
//						}
					}else if(obj2.getType()==4){ //如果是目的地DES
						//如果是8:短途运输类型的(永远在两侧显示)
//						if(obj2.getItem().getType()==8){
//							workItem6.add(obj2);
//						}else{
							workItem5.add(obj2);
//						}
					}
				}
				work.setOption13(items);
			}
		
			request.setAttribute("workItem1", workItem1);//出发地ORG的委托项目短途运输类型list
			request.setAttribute("workItem2", workItem2);//出发地ORG的委托项目非短途运输类型list
			request.setAttribute("workItem3", workItem3);//出发港POL的委托项目list
			request.setAttribute("workItem4", workItem4);//到达港POD的委托项目list
			request.setAttribute("workItem5", workItem5);//目的地DES的委托项目非短途运输类型list
			request.setAttribute("workItem6", workItem6);//目的地DES的委托项目短途运输类型list
			
			List<WorkDoc> workDocsList = this.commonManager.findByCustomizedSQL(WorkDoc.class, " parentId is null and workId = " + work.getId());
			request.setAttribute("workDocsList", workDocsList);//文档list
			
			if(!CommUtils.isCorrectNumber(userId)){
				return null;
			}
			int authType=-1;
			if(workTeamList!=null){
				for (WorkTeam team : workTeamList) {
					if(team.getEmployee().getUser().getId()==Long.parseLong(userId)){
						authType=team.getAuth();
						break;
					}
				}
			}
			//如果管理员的公司员工创建的订单，管理员也有权限操作该订单
			if(work.getCompany().getUser().getId()==Long.parseLong(userId)){
				authType=1;
			}
			request.setAttribute("authType", authType);
			
			List<ContainerNo> containerNoList=this.commonManager.findByCustomizedSQL(ContainerNo.class, " workId = "+work.getId());
			request.setAttribute("containerNoList", containerNoList);
			request.setAttribute("boxTxt", ActionUtil.boxTxt);
			
			//算出发时间到到达时间的百分比
			Date beginDate=null;
			Date nowDate=new Date();
			Date endDate=null;
			if((work.getPointORG()!=null || work.getPointPOL()!=null) && (work.getPointPOD()!=null || work.getPointDES()!=null)){
				if(work.getItem().getType()<4){
					if(work.getPointORG().getId()==work.getPointPOL().getId()){
						beginDate=work.getDepartureTime2();
					}else{
						beginDate=work.getDepartureTime1();
					}
					if(work.getPointPOD().getId()==work.getPointDES().getId()){
						endDate=work.getArrivalTime1();
						if(endDate==null){
							endDate=work.getEta1();
						}
					}else{
						endDate=work.getArrivalTime2();
						if(endDate==null){
							endDate=work.getEtd2();
						}
					}
				}else if(work.getItem().getType()==4){
					beginDate=work.getExpressGetTime();
					endDate=work.getExpressPutTime();
					if(endDate==null){
						endDate=work.getExpressETA();
					}
				}else if(work.getItem().getType()==5){
					beginDate=work.getTruckingTime1();
					endDate=work.getTruckingTime2();
					if(endDate==null){
						endDate=work.getTruckingETA();
					}
				}
				if(beginDate!=null && endDate!=null){
					int m1=TimeUtil.minutesOfTwo(beginDate, endDate);
					int m2=TimeUtil.minutesOfTwo(beginDate, nowDate);
					
					double mPercent=(double)m2/m1;
					if(mPercent<0){
						mPercent=0;
					}else if(mPercent>1){
						mPercent=1;
					}
					BigDecimal b=new BigDecimal(mPercent);
					mPercent=b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					request.setAttribute("percent", mPercent);//计算用的百分比（如0.85）
				}
			}
			//主航线的天数
			if(beginDate!=null && endDate!=null){
				int totalDay=TimeUtil.daysOfTwo(beginDate,endDate);
				request.setAttribute("totalDay", totalDay+1);
			}
			
			
			String tags = work.getTags();
			if( tags!=null && tags.trim().length()>0){
				List<Tag> option15 = new ArrayList<Tag>();
				String arr[] = new StringBuffer(tags).toString().split(",");
				for( String obj2: arr ){
					if( CommUtils.isCorrectNumber(obj2)){
						Tag tag = this.commonManager.findEntityByPK( Tag.class, Long.parseLong(obj2));
						option15.add( tag );
					}
				}
				work.setOption15(option15);//标签列表
			}
		}else{
			request.setAttribute("msg", "该订单不存在！");
			return "work/noWorkDetail";
		}
		
		
		/*------------页面测试数据
		Date beginDate=TimeUtil.controlTime("2012-03-12 11:10");
		Date nowDate=TimeUtil.controlTime("2012-03-13 12:38");
		Date endDate=TimeUtil.controlTime("2012-03-18 11:10");
		
		int m1=TimeUtil.minutesOfTwo(beginDate, endDate);
		int m2=TimeUtil.minutesOfTwo(beginDate, nowDate);
		
		double mPercent=(double)m2/m1;
		if(mPercent<0){
			mPercent=0;
		}else if(mPercent>1){
			mPercent=1;
		}
		
		BigDecimal b=new BigDecimal(mPercent);
		mPercent=b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
		
		request.setAttribute("percent", mPercent);
		List<String> tagsList=new ArrayList<String>(){};
		tagsList.add("加急");
		tagsList.add("公司货");
		for(int i=1;i<7;i++) {
			tagsList.add("TAG"+i);
		}
		request.setAttribute("tagsList", tagsList);
		------------页面测试数据*/
		return "work/workDetail";
	}
	
	/**
	 * work列表
	 * @return
	 */
	@Action("searchWork")
	public String searchWork(){
		HttpServletRequest request=ServletActionContext.getRequest();
		String isContentFlag = request.getParameter("isContentFlag");
		
		String userId = CookieUtil.getCookieValue(request, "cts_userid");
		if(!CommUtils.isCorrectNumber(userId)){
			return null;
		}
		User user = this.commonManager.findEntityByPK( User.class, Long.parseLong(userId));
		String cts_employeecpyid = CookieUtil.getCookieValue(request, "cts_employeecpyid");
		Employee e = this.commonManager.findEntityByPK(Employee.class, Long.parseLong(cts_employeecpyid));
		
		Company company = e.getCompany();
		request.setAttribute("e", e);
		
		if( isContentFlag == null ){
			ActionUtil.getTopAllInfo();
			request.setAttribute("carrier_fcl", ActionUtil.getCompanyParam(company, 1, 5, 7, 0));
			request.setAttribute("carrier_lcl", ActionUtil.getCompanyParam(company, 2, 5, 7, 0));
			request.setAttribute("carrier_air", ActionUtil.getCompanyParam(company, 3, 5, 7, 0));
			request.setAttribute("expressCarrier_exp", ActionUtil.getCompanyParam(company, 4, 5, 7, 0));
			//request.setAttribute("items", ActionUtil.getCompanyParam(company, null, 1, null, 0));
//			if(request.getParameter("keyword")!=null && !"".equals(request.getParameter("keyword"))){
				keyword=request.getParameter("keyword");
//			}
			return "work/searchwork";
		}
		
		String seachType = request.getParameter("seachType");//判定是普通搜索（or）或是高级搜索1，为普通，默认为普通，2为高级搜索
		String itemType = request.getParameter("itemType");
		String workingStatus = request.getParameter("workingStatus");
		if( itemType == null )itemType = "0";
		if( workingStatus == null ) workingStatus = "0";
		if( seachType == null ) seachType = "1";
		List<Work> workResult = null;
		
		
		Map<String,String> workConditions = new HashMap<String,String>();
		if( !itemType.equals("0")){
			workConditions.put("item.type", itemType );
		}
		if( !workingStatus.equals("0")){
			workConditions.put("workingStatus", workingStatus );
		}
		
		Map<String,String> workItemConditions = new HashMap<String,String>();
		Map<String,String> workTeamConditions = new HashMap<String,String>();
		Map<String,String> tagConditions = new HashMap<String,String>();
		if( seachType.equals("1")){
			if( keyword!=null && keyword.trim().length()>0 && !keyword.equals(this.getText("cts.work.searchDefault"))){
				keyword = keyword.trim();
				workConditions.put("workCode", keyword );
				//workConditions.put("client1.nickname", keyword );
				//workConditions.put("cargoName", keyword );
				
				//workItemConditions.put("service.user.userName",keyword);
				//workItemConditions.put("item.name_zh",keyword);
				
				//workTeamConditions.put("employee.user.userName", keyword );
				
				//tagConditions.put( "name", keyword );
			}
			try {
				workResult = this.workManager.getWorkByOrConditions(company, user,e, workConditions, workItemConditions, workTeamConditions, tagConditions, pageSize, pageNumber);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}else{
			String workCode = request.getParameter("workCode").trim();
			String client1 = request.getParameter("client1").trim();
			String delegateTime = request.getParameter("delegateTime").trim();
			String team = request.getParameter("team").trim();
			String tag = request.getParameter("tag").trim();
			String cargoName = request.getParameter("cargoName").trim();
			String startTime = request.getParameter("startTime").trim();
			String endTime = request.getParameter("endTime").trim();
			String serviceName = request.getParameter("serviceName").trim();
			String itemName = request.getParameter("itemName").trim();
			if( CommUtils.isValidStr(workCode)){
				workConditions.put("workCode|", workCode );
			}
			if( CommUtils.isValidStr(client1)){
				workConditions.put("client1.nickname|", client1 );
			}
			if( CommUtils.isValidStr(delegateTime)){
				workConditions.put("delegateTime", delegateTime );
			}
			if( CommUtils.isValidStr(team)){
				workTeamConditions.put("employee.nickname|", team );
			}
			if( CommUtils.isValidStr(tag)){
				tagConditions.put( "name|", tag );
			}
			if( CommUtils.isValidStr(cargoName)){
				workConditions.put( "cargoName|", cargoName );
			}
			if( CommUtils.isValidStr(startTime)){
				workItemConditions.put( "startTime", startTime );
			}
			if( CommUtils.isValidStr(endTime)){
				workItemConditions.put( "endTime", endTime );
			}
			if( CommUtils.isValidStr(serviceName)){
				workItemConditions.put( "service.nickname|", serviceName );
			}
			
			if( CommUtils.isValidStr(itemName)){
				workItemConditions.put( "item.name_zh|", itemName );
			}
			
			
			if( itemType.equals("1") || itemType.equals("2")){//FCL或者LCL
				String pointORGName_fcl_id = request.getParameter("pointORGName_fcl_id").trim();
				String pointDES_fcl_id = request.getParameter("pointDES_fcl_id").trim();
				String boxAmount_fcl = request.getParameter("boxAmount_fcl").trim();
				String oceanVessel1_fcl = request.getParameter("oceanVessel1_fcl").trim();
				String bookingNumber_fcl = request.getParameter("bookingNumber_fcl").trim();
				String blNumber_fcl = request.getParameter("blNumber_fcl").trim();
				String carrierName_fcl = request.getParameter("carrierName_fcl").trim();
				if( CommUtils.isCorrectNumber(pointORGName_fcl_id) && !pointORGName_fcl_id.equals("0")){
					workConditions.put("pointORG.id", pointORGName_fcl_id);
				}
				if( CommUtils.isCorrectNumber(pointDES_fcl_id) && !pointDES_fcl_id.equals("0")){
					workConditions.put("pointDES.id", pointDES_fcl_id);
				}
				if( CommUtils.isValidStr(boxAmount_fcl)){
					workConditions.put( "boxAmount|", boxAmount_fcl );
				}
				if( CommUtils.isValidStr(oceanVessel1_fcl)){
					workConditions.put( "oceanVessel1|", oceanVessel1_fcl );
				}
				if( CommUtils.isValidStr(bookingNumber_fcl)){
					workConditions.put( "bookingNumber|", bookingNumber_fcl );
				}
				if( CommUtils.isValidStr(bookingNumber_fcl)){
					workConditions.put( "bookingNumber|", bookingNumber_fcl );
				}
				if( CommUtils.isValidStr(blNumber_fcl)){
					workConditions.put( "blNumber|", blNumber_fcl );
				}
				if( CommUtils.isCorrectNumber(carrierName_fcl) && !carrierName_fcl.equals("0")){
					workConditions.put( "carrier.id", carrierName_fcl );
				}
			}else if(itemType.equals("3")){//AIR
				String pointORG_air_id = request.getParameter("pointORG_air_id").trim();
				String pointDES_air_id = request.getParameter("pointDES_air_id").trim();
				String voyNo2_air = request.getParameter("voyNo2_air").trim();
				String bookingNumber_air = request.getParameter("bookingNumber_air").trim();
				String carrier_air = request.getParameter("carrier_air").trim();
				
				if( CommUtils.isCorrectNumber(pointORG_air_id) && !pointORG_air_id.equals("0")){
					workConditions.put("pointORG.id", pointORG_air_id);
				}
				if( CommUtils.isCorrectNumber(pointDES_air_id) && !pointDES_air_id.equals("0")){
					workConditions.put("pointDES.id", pointDES_air_id);
				}
				if( CommUtils.isValidStr(voyNo2_air)){
					workConditions.put("voyNo2|", voyNo2_air);
				}
				if( CommUtils.isValidStr(bookingNumber_air)){
					workConditions.put("bookingNumber|", bookingNumber_air);
				}
				if( CommUtils.isCorrectNumber(carrier_air) && !carrier_air.equals("0")){
					workConditions.put( "carrier.id", carrier_air );
				}
			}else if(itemType.equals("4")){//EXPRESS
				String expressExportCountry_exp_id = request.getParameter("expressExportCountry_exp_id").trim();
				String expressImportCountry_exp_id = request.getParameter("expressImportCountry_exp_id").trim();
				String expressBookingNumber_exp = request.getParameter("expressBookingNumber_exp").trim();
				String expressCarrier_exp = request.getParameter("expressCarrier_exp").trim();
				if( CommUtils.isCorrectNumber(expressExportCountry_exp_id) && !expressExportCountry_exp_id.equals("0")){
					workConditions.put("expressExportCountry.id", expressExportCountry_exp_id);
				}
				if( CommUtils.isCorrectNumber(expressImportCountry_exp_id) && !expressImportCountry_exp_id.equals("0")){
					workConditions.put("expressImportCountry.id", expressImportCountry_exp_id);
				}
				if( CommUtils.isValidStr(expressBookingNumber_exp)){
					workConditions.put("expressBookingNumber|", expressBookingNumber_exp);
				}
				if( CommUtils.isCorrectNumber(expressCarrier_exp)  && !expressCarrier_exp.equals("0")){
					workConditions.put( "expressCarrier.id", expressCarrier_exp );
				}
			}else if(itemType.equals("5")){//TRUCKING
				String pointORG_car_id = request.getParameter("pointORG_car_id").trim();
				String pointDES_car_id = request.getParameter("pointDES_car_id").trim();
				String truckingCarNumber_car = request.getParameter("truckingCarNumber_car").trim();
				String bookingNumber_car = request.getParameter("bookingNumber_car").trim();
				String boxAmount_car = request.getParameter("boxAmount_car").trim();
				
				if( CommUtils.isCorrectNumber(pointORG_car_id) && !pointORG_car_id.equals("0")){
					workConditions.put("pointORG.id", pointORG_car_id);
				}
				if( CommUtils.isCorrectNumber(pointDES_car_id)  && !pointDES_car_id.equals("0")){
					workConditions.put("pointDES.id", pointDES_car_id);
				}
				if( CommUtils.isValidStr(truckingCarNumber_car)){
					workConditions.put("truckingCarNumber|", truckingCarNumber_car);
				}
				if( CommUtils.isValidStr(bookingNumber_car)){
					workConditions.put("bookingNumber|", bookingNumber_car);
				}
				if( CommUtils.isValidStr(boxAmount_car)){
					workConditions.put("boxAmount|", boxAmount_car);
				}
			}else if(itemType.equals("6")){//其他
				
			}
			try {
				workResult = this.workManager.getWorkByAndConditions(company, user,e, workConditions, workItemConditions, workTeamConditions, tagConditions, pageSize, pageNumber);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		fillData( request,workResult );
		
		return "work/workresult";
	}
	
	public void main( String args[] ){
		
	}
	//給结果记录集填充临时值
	private void fillData( HttpServletRequest request,List<Work> workResult ){
		if( workResult == null || workResult.size()==0 ) return;
		for( Work obj: workResult ){
			
			List<WorkFee> fees1 = this.workManager.getFeesByWork( obj, 0 );// 应收款
			List<WorkFee> fees2 = this.workManager.getFeesByWork( obj, 1 );// 应付款
			obj.setOption11(fees1);
			obj.setOption12(fees2);
			
			List<WorkItem> items = this.workManager.getItemsByWork( obj );//其他委托项目
			if( items!=null && items.size()>0 ){
				for( WorkItem obj2: items ){
					if( obj2.getEndTime()!=null && TimeUtil.dateIsPass(obj2.getEndTime())){
						obj2.setOption1(1);//任务已经完成
					}else{
						obj2.setOption1(0);
					}
				}
				obj.setOption13(items);
			}
		
			//算出发时间到离港时间差值
			
			Date date1=null;
			Date date2=null;
			if((obj.getPointORG()!=null || obj.getPointPOL()!=null) && (obj.getPointPOD()!=null || obj.getPointDES()!=null)){
				if(obj.getItem().getType()<4 || obj.getItem().getType() >5){
					//date1=obj.getDepartureTime1();
					//date2=obj.getArrivalTime2();
					if(obj.getPointORG().getId()==obj.getPointPOL().getId()){
						date1=obj.getDepartureTime2();
						if( date1 == null ){
							date1 = obj.getEtd2();
							obj.setOption3("1");
						}
					}else{
						date1=obj.getDepartureTime1();
						if( date1 == null ){
							date1 = obj.getEtd1();
							obj.setOption3("1");
						}
					}
					if(obj.getPointPOD().getId()==obj.getPointDES().getId()){
						date2=obj.getArrivalTime1();
						if( date2 == null ){
							date2 = obj.getEta1();
							obj.setOption4("1");
						}
					}else{
						date2=obj.getArrivalTime2();
						if( date2 == null ){
							date2 = obj.getEta2();
							obj.setOption4("1");
						}
					}
					
				}else if(obj.getItem().getType()==4){
					date1=obj.getExpressGetTime();
					date2=obj.getExpressPutTime();
					if( date1 == null ){
						date1 = obj.getExpressETD();
						obj.setOption3("1");
					}
					if( date2 == null ){
						date2 = obj.getExpressETA();
						obj.setOption4("1");
					}
					
				}else if(obj.getItem().getType()==5){
					date1=obj.getTruckingTime1();
					date2=obj.getTruckingTime2();
					if( date1 == null ){
						date1 = obj.getTruckingETD();
						obj.setOption3("1");
					}
					if( date2 == null ){
						date2 = obj.getTruckingETA();
						obj.setOption4("1");
					}
				}
			}
			if( date1 !=null && date2 !=null ){
				if( obj.getItem().getType() == 3 ){//如果是空港
					int hours = TimeUtil.hourOfTwo(date1,date2);
					int hour = hours%24;
					int day = hours/24;
					obj.setOption2( day+"天"+hour+"小时");
				}else{
					obj.setOption2( TimeUtil.daysOfTwo(date1,date2)+"天");
				}
			}
			obj.setOption16( date1 );
			obj.setOption17( date2 );
			String tags = obj.getTags();
			if( tags!=null && tags.trim().length()>0){
				List<Tag> option15 = new ArrayList<Tag>();
				String arr[] = tags.split(",");
				int i=1;
				for( String obj2: arr ){
					if( CommUtils.isCorrectNumber(obj2)){
						Tag tag = this.commonManager.findEntityByPK( Tag.class, Long.parseLong(obj2));
						Tag newObj = new Tag();
						newObj.setName( tag.getName());
						newObj.setOption1( String.valueOf( i ));
						option15.add( newObj );
						i++;
						if( i == 7 ){
							i = 1;
						}
					}
				}
				Collections.reverse(option15);
				obj.setOption15(option15);
			}
		}
		request.setAttribute("workResult", workResult);
	}
	
	/**
	 * 获取work状态数目
	 */
	@Action("getCountByStatus")
	public void getCountByStatus(){
		String result = "";
		
		try {
			HttpServletRequest request=ServletActionContext.getRequest();
			String userId = CookieUtil.getCookieValue(request, "cts_userid");
			User user = this.commonManager.findEntityByPK( User.class, Long.parseLong(userId));
			String cts_employeecpyid = CookieUtil.getCookieValue(request, "cts_employeecpyid");
			Employee e = this.commonManager.findEntityByPK(Employee.class, Long.parseLong(cts_employeecpyid));
			Company company = e.getCompany();
			List<Work> list = this.workManager.getWorkByOrConditions(company, user,e, null, null, null, null, 10000, 1);
			for( Work obj: list ){
				this.workManager.updateWorkStatus( obj );
			}
			int s1 = this.workManager.getCountByStatus(company, user,e, 1);
			int s2 = this.workManager.getCountByStatus(company, user, e,2);
			int s3 = this.workManager.getCountByStatus(company, user,e, 3);
			int s4 = this.workManager.getCountByStatus(company, user, e,4);
			int s5 = this.workManager.getCountByStatus(company, user, e,5);
			result +=s1+","+s2+","+s3+","+s4+","+s5+",";
		} catch (Exception e) {
			e.printStackTrace();
		}
		ActionUtil.outputData(result);
	}
	
	/**
	 * 获取work状态数目
	 */
	@Action("getCountByType")
	public void getCountByType(){
		String result = "";
		try {
			HttpServletRequest request=ServletActionContext.getRequest();
			String userId = CookieUtil.getCookieValue(request, "cts_userid");
			User user = this.commonManager.findEntityByPK( User.class, Long.parseLong(userId));
			String cts_employeecpyid = CookieUtil.getCookieValue(request, "cts_employeecpyid");
			Employee e = this.commonManager.findEntityByPK(Employee.class, Long.parseLong(cts_employeecpyid));
			Company company = e.getCompany();
			
			List<Work> list = this.workManager.getWorkByOrConditions(company, user,e, null, null, null, null, 10000, 1);
			for( Work obj: list ){
				this.workManager.updateWorkStatus( obj );
			}
			int s1 = this.workManager.getCountByType(company, user,e, "FCL");
			int s2 = this.workManager.getCountByType(company, user, e,"LCL");
			int s3 = this.workManager.getCountByType(company, user, e,"AIR");
			int s4 = this.workManager.getCountByType(company, user, e,"EXPRESS");
			int s5 = this.workManager.getCountByType(company, user, e,"TRUCKING");
			int s6 = this.workManager.getCountByType(company, user, e,"other");
			result +=s1+","+s2+","+s3+","+s4+","+s5+","+s6+",";
		} catch (Exception e) {
			e.printStackTrace();
		}
		ActionUtil.outputData(result);
	}
	
	
	@Action("workDetailItem")
	public String getWorkDetailItem(){
		HttpServletRequest request=ServletActionContext.getRequest();
		String workType = request.getParameter("workType");
		request.setAttribute("workType", workType);// 订单类型（1：FCL 2:LCL 3:AIR 4:EXPRESS 5:TRUCKING else:OTHER）
		
		String idStr=request.getParameter("id");
		long id=0;
		if(idStr!=null && !"".equals(idStr)){
			id=Long.parseLong(idStr);
		}
		if(workType!=null && !"".equals(workType)){
			work=this.commonManager.findEntityByPK(Work.class, id);
			List<WorkTeam> workTeamList=this.commonManager.findByCustomizedSQL(WorkTeam.class, " workId = "+work.getId());
			String employeeIdStr = CookieUtil.getCookieValue(request, "cts_employeecpyid");
			long employeeId=0;
			if(employeeIdStr!=null && !"".equals(employeeIdStr)){
				employeeId=Long.parseLong(employeeIdStr);
			}
			boolean ifTeamMember=false;
			for (WorkTeam team : workTeamList) {
				if(employeeId==team.getEmployee().getId()){
					ifTeamMember=true;
					break;
				}
			}
			String userId = CookieUtil.getCookieValue(request, "cts_userid");
			//如果管理员的公司员工创建的订单，管理员也有权限操作该订单
			if(work.getCompany().getUser().getId()==Long.parseLong(userId)){
				ifTeamMember=true;
			}
			
			request.setAttribute("ifTeamMember", ifTeamMember);
			
			List<WorkFee> workFeeList = this.workManager.getFeesByWork( work, 1 );// 应付款
			List<WorkFee> temp=new ArrayList<WorkFee>();
			for(WorkFee f : workFeeList){
				if(f.getWorkItem()==null){
					temp.add(f);
				}
				
			}
			request.setAttribute("workFeeList", temp);
		}else{
			workItem=this.commonManager.findEntityByPK(WorkItem.class, id);
			List<WorkFee> workFeeList = this.workManager.getFeesByWork( workItem.getWork(), 1 );// 应付款
			List<WorkFee> temp=new ArrayList<WorkFee>();
			for(WorkFee f : workFeeList){
				if(f.getWorkItem()!=null && f.getWorkItem().getId()==workItem.getId()){
					temp.add(f);
				}
				
			}
			request.setAttribute("workFeeList", temp);
		}
		
		return "work/workDetailItem"; 
	}
	
	@Action("updateWorkStatus")
	public void updateWorkStatus(){
		try {
			HttpServletRequest request=ServletActionContext.getRequest();
			String workId = request.getParameter("id");
			String status=request.getParameter("status");//5：已归档 6：删除
			Work work=this.commonManager.findEntityByPK(Work.class, Long.parseLong(workId));
			//如果要进行归档（归档的条件是：所有任何已完成和所有应付款已结清）
			if("5".equals(status)){
				boolean flag=true;
				List<WorkFee> feeList = this.workManager.getFeesByWork( work, 1 );//应付款
				for (WorkFee fee : feeList) {
					if(!fee.getWrittenOffmoney().equals(fee.getMoney())){//已结算金额不等于应结算金额
						flag=false;
						break;
					}
				}
				//如果应付款未结清或者所有任务没有完成
				if(work.getWorkingStatus()!=3 || flag==false){
					ActionUtil.outputData(-1);
					return;
				}
			}
			work.setWorkingStatus(Integer.parseInt(status));
			this.commonManager.modifyEntity(work);
			ActionUtil.outputData(status);
		} catch (Exception e) {
			ActionUtil.outputData(1);
		}
	}
	//进入统计
	@Action("toStatisticalWorks")
	public String toStatisticalWorks(){
		HttpServletRequest request=ServletActionContext.getRequest();
		int statisticalType = 1;
		Employee employee = ActionUtil.getSelectEmployee();
		Company company = employee.getCompany();
		String statisticalTypeStr = request.getParameter("statisticalType");
		request.setAttribute("company", company);
		request.setAttribute("employee", employee);
		if(CommUtils.isCorrectInt(statisticalTypeStr)){
			statisticalType = Integer.parseInt(statisticalTypeStr);
		}
		if(statisticalType >= 3){
			request.setAttribute("items", ActionUtil.getCompanyParam(company, null, 1, null, 0));
		}
		List<Currency> currencys = ActionUtil.getCompanyParam(company, 0, 0, 0, null);
		request.setAttribute("currencys", currencys);
		request.setAttribute("statisticalType", statisticalType);
		return "work/statisticalWorks"; 
	}
	//筛选统计 statisticalType:1-奖励统计，2毛利统计，3订单统计
	@Action("statisticalWorks")
	public String statisticalWorks(){
		HttpServletRequest request=ServletActionContext.getRequest();
		String language = CookieUtil.getCookieValue(request, "cts_locale");
		String statisticalTypeStr = request.getParameter("statisticalType");
		String companyId = request.getParameter("companyId");
		String employeeId = request.getParameter("employeeId");
		String currencyId = request.getParameter("currency");
		int statisticalType = 1;
		Company company = null;
		Employee employee = null;
		Currency currency = null;
		if(CommUtils.isCorrectInt(statisticalTypeStr)){
			statisticalType = Integer.parseInt(statisticalTypeStr);
		}
		if(CommUtils.isCorrectInt(companyId)){
			company = commonManager.findEntityByPK(Company.class, Long.parseLong(companyId));
		}
		if(CommUtils.isCorrectInt(employeeId)){
			employee = commonManager.findEntityByPK(Employee.class, Long.parseLong(employeeId));
		}
		if(CommUtils.isCorrectInt(currencyId)){
			currency = commonManager.findEntityByPK(Currency.class, Long.parseLong(currencyId));
		}
		Map<String, Object> conditions = getConditions();
		List<Work> list = this.workManager.statisticalWorks(company, statisticalType, true, conditions, 1, 1);
		
		float total = 0f;
		if(statisticalType < 3){
			for(int i=0; i< list.size(); i++){
				Work w = list.get(i);
				conditions.put("employeeId", w.getEmployee().getId());
				conditions.put("month", TimeUtil.getYY(w.getDelegateTime()) + "-"+TimeUtil.getMM(w.getDelegateTime()));
				List<Work> list2 =  this.workManager.statisticalWorks(company, statisticalType, false, conditions, 1, 1);
				float f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0;
				for (int j = 0; j < list2.size(); j++) {
					float[] result = null;
					result = workManager.countWorkFees(list2.get(j),currency);
					f1 += result[0];  	
					f2 += result[1];  	
					f3 += result[2];	
					f4 += result[3];	
					f5 += result[4];
				}
				w.setOption2(CommUtils.twoFractionDigits(f1));//应收费用合计
				w.setOption3(CommUtils.twoFractionDigits(f2));//应付费用合计
				w.setOption4(CommUtils.twoFractionDigits(f3));//奖励合计
				w.setOption5(CommUtils.twoFractionDigits(f4));//毛利润
				w.setOption6(CommUtils.twoFractionDigits(f5));//公司利润
				if (statisticalType == 1) {
					total += f3;
				}else if(statisticalType == 2){
					total += f4;
				}
				w.getItem().setName(!language.equals("zh_CH") ? w.getItem().getName_en() : w.getItem().getName_zh());
			}
			request.setAttribute("total",CommUtils.twoFractionDigits(total));
		}else{
			Work tempWork = null;
			int eTotal = 0;
			for(int i=0; i< list.size(); i++){
				Work w = list.get(i);
				if(tempWork == null || tempWork.getEmployee().getId() != w.getEmployee().getId()){
					if(tempWork != null){
						tempWork.setOption2(eTotal+"");
					}
					tempWork = w;
					eTotal = Integer.parseInt(w.getOption1());
					tempWork.setOption2(eTotal+"");
				}else{
					eTotal += Integer.parseInt(w.getOption1());
				}
				w.getItem().setName(!language.equals("zh_CH") ? w.getItem().getName_en() : w.getItem().getName_zh());
			}
			if(tempWork != null){
				tempWork.setOption2(eTotal+"");
			}
			request.setAttribute("total",conditions.get("workTotal"));
		}
		request.setAttribute("workList", list);
		request.setAttribute("statisticalType", statisticalType);
		return "work/statisticalGroup"; 
	}

	@Action("statisticalItems")
	public String statisticalItems(){
		HttpServletRequest request=ServletActionContext.getRequest();
		String language = CookieUtil.getCookieValue(request, "cts_locale");
		String statisticalTypeStr = request.getParameter("statisticalType");
		String companyId = request.getParameter("companyId");
		String employeeId = request.getParameter("employeeId");
		String currencyId = request.getParameter("currency");
		String itemType = request.getParameter("itemTypeId");
		int statisticalType = 1;
		Company company = null;
		Employee employee = null;
		Currency currency = null;
		if(CommUtils.isCorrectInt(statisticalTypeStr)){
			statisticalType = Integer.parseInt(statisticalTypeStr);
		}
		Map<String, Object> conditions = getConditions();
		if(CommUtils.isCorrectInt(companyId)){
			company = commonManager.findEntityByPK(Company.class, Long.parseLong(companyId));
		}
		if(CommUtils.isCorrectInt(employeeId)){
			employee = commonManager.findEntityByPK(Employee.class, Long.parseLong(employeeId));
		}
		if(CommUtils.isCorrectInt(currencyId)){
			currency = commonManager.findEntityByPK(Currency.class, Long.parseLong(currencyId));
		}
		if(statisticalType >= 3){
			if(CommUtils.isCorrectInt(itemType)){
				conditions.put("itemType", itemType); 
			}
		}
		conditions.put("employeeId", employee.getId());
		List<Work> list =  this.workManager.statisticalWorks(company, statisticalType, false, conditions, 1, 1);
		if(statisticalType == 1){  //奖励统计
			Map<Long, Work> workMap = new HashMap<Long, Work>();
			List<WorkFee> workFees = new ArrayList<WorkFee>();
			for (int i = 0; i < list.size(); i++) {
				Work w = list.get(i);
				String sql = "type = 2 and workId = " + w.getId();
				if("1".equals(request.getParameter("status1"))){
					sql += " and rewardTime is null";
				}
				List<WorkFee> fees = this.commonManager.findByCustomizedSQL(WorkFee.class, sql);
				workFees.addAll(fees);
				float[] result = workManager.countWorkFees(w,currency);
				w.setOption2(CommUtils.twoFractionDigits(result[0]));//应收费用合计
				w.setOption3(CommUtils.twoFractionDigits(result[1]));//应付费用合计
				w.setOption4(CommUtils.twoFractionDigits(result[2]));//奖励合计
				w.setOption5(CommUtils.twoFractionDigits(result[3]));//毛利润
				w.setOption6(CommUtils.twoFractionDigits(result[4]));//应公司利润
				workMap.put(w.getId(), w);
			}
			
			for (int i = 0; i < workFees.size(); i++) {
				WorkFee fee = workFees.get(i);
				Work w = new Work();
				try {
					CommUtils.copyProperties(w, fee.getWork());
				} catch (Exception e) {
					e.printStackTrace();
				}
				fee.setWork(w);
				w.setOption4(workManager.countWorkFee(fee, currency) + "");
				w.setOption2(workMap.get(w.getId()).getOption2());
				w.setOption3(workMap.get(w.getId()).getOption3());
				w.setOption5(workMap.get(w.getId()).getOption5());
				w.setOption6(workMap.get(w.getId()).getOption6());
				w.getItem().setName(!language.equals("zh_CH") ? w.getItem().getName_en() : w.getItem().getName_zh());
			}
			request.setAttribute("currency", currency);
			request.setAttribute("workFees", workFees);
		}else if(statisticalType == 2){
			for (int i = 0; i < list.size(); i++) {
				Work w = list.get(i);
				float[] result = workManager.countWorkFees(w,currency);
				w.setOption2(CommUtils.twoFractionDigits(result[0]));//应收费用合计
				w.setOption3(CommUtils.twoFractionDigits(result[1]));//应付费用合计
				w.setOption4(CommUtils.twoFractionDigits(result[2]));//奖励合计
				w.setOption5(CommUtils.twoFractionDigits(result[3]));//毛利润
				w.setOption6(CommUtils.twoFractionDigits(result[4]));//应公司利润
				w.getItem().setName(!language.equals("zh_CH") ? w.getItem().getName_en() : w.getItem().getName_zh());
			}
			request.setAttribute("workList", list);
		}else if(statisticalType >= 3){
			Item item = commonManager.findEntityByPK(Item.class, Long.parseLong(itemType));
			request.setAttribute("item", item);
			request.setAttribute("workList", list);
		}
		request.setAttribute("statisticalType", statisticalType);
		return "work/statisticalItems"; 
	}
	
	@Action("exportStatisticsWorks")
	public void exportStatisticsWorks(){
		HttpServletRequest request=ServletActionContext.getRequest();
		try{
			String language = CookieUtil.getCookieValue(request, "cts_locale");
			String statisticalTypeStr = request.getParameter("statisticalType");
			String companyId = request.getParameter("companyId");
			String employeeId = request.getParameter("employeeId");
			String currencyId = request.getParameter("currency");
			int statisticalType = 1;
			Company company = null;
			Employee employee = null;
			Currency currency = null;
			if(CommUtils.isCorrectInt(statisticalTypeStr)){
				statisticalType = Integer.parseInt(statisticalTypeStr);
			}
			if(CommUtils.isCorrectInt(companyId)){
				company = commonManager.findEntityByPK(Company.class, Long.parseLong(companyId));
			}
			if(CommUtils.isCorrectInt(employeeId)){
				employee = commonManager.findEntityByPK(Employee.class, Long.parseLong(employeeId));
			}
			if(CommUtils.isCorrectInt(currencyId)){
				currency = commonManager.findEntityByPK(Currency.class, Long.parseLong(currencyId));
			}
			Map<String, Object> conditions = getConditions();
			List<Work> list = this.workManager.statisticalWorks(company, statisticalType, false, conditions, 1, 1);
			List<WorkFee> workFees = null;
			if(statisticalType == 1){  //奖励统计
				Map<Long, Work> workMap = new HashMap<Long, Work>();
				workFees = new ArrayList<WorkFee>();
				for (int i = 0; i < list.size(); i++) {
					Work w = list.get(i);
					String sql = "type = 2 and workId = " + w.getId();
					if("1".equals(request.getParameter("status1"))){
						sql += " and rewardTime is null";
					}
					List<WorkFee> fees = this.commonManager.findByCustomizedSQL(WorkFee.class, sql);
					workFees.addAll(fees);
					float[] result = workManager.countWorkFees(w,currency);
					w.setOption2(CommUtils.twoFractionDigits(result[0]));//应收费用合计
					w.setOption3(CommUtils.twoFractionDigits(result[1]));//应付费用合计
					w.setOption4(CommUtils.twoFractionDigits(result[2]));//奖励合计
					w.setOption5(CommUtils.twoFractionDigits(result[3]));//毛利润
					w.setOption6(CommUtils.twoFractionDigits(result[4]));//应公司利润
					workMap.put(w.getId(), w);
				}
				
				for (int i = 0; i < workFees.size(); i++) {
					WorkFee fee = workFees.get(i);
					Work w = new Work();
					try {
						CommUtils.copyProperties(w, fee.getWork());
					} catch (Exception e) {
						e.printStackTrace();
					}
					fee.setWork(w);
					w.setOption4(workManager.countWorkFee(fee, currency) + "");
					w.setOption2(workMap.get(w.getId()).getOption2());
					w.setOption3(workMap.get(w.getId()).getOption3());
					w.setOption5(workMap.get(w.getId()).getOption5());
					w.setOption6(workMap.get(w.getId()).getOption6());
				}
			}else if(statisticalType == 2){
				for (int i = 0; i < list.size(); i++) {
					Work w = list.get(i);
					float[] result = workManager.countWorkFees(w,currency);
					w.setOption2(CommUtils.twoFractionDigits(result[0]));//应收费用合计
					w.setOption3(CommUtils.twoFractionDigits(result[1]));//应付费用合计
					w.setOption4(CommUtils.twoFractionDigits(result[2]));//奖励合计
					w.setOption5(CommUtils.twoFractionDigits(result[3]));//毛利润
					w.setOption6(CommUtils.twoFractionDigits(result[4]));//应公司利润
				}
			}
			
			
			ExportExcel excel = new ExportExcel();
			List<List<ExcelProperty>> reList = new ArrayList<List<ExcelProperty>>();
			List<List<ExcelTitle>> tiList = new ArrayList<List<ExcelTitle>>();
			List<List<ExcelTitle>> heList = new ArrayList<List<ExcelTitle>>();
			List<ExcelProperty> dataList = null;
			String title = null;
			if(statisticalType == 1){
				dataList = new ArrayList<ExcelProperty>();
				dataList.add(new ExcelProperty("订单委托月份", dataList.size()));
				dataList.add(new ExcelProperty("委托方", dataList.size()));
				dataList.add(new ExcelProperty("订单号", dataList.size()));
				dataList.add(new ExcelProperty("委托项目", dataList.size()));
				dataList.add(new ExcelProperty("货量", dataList.size()));
				dataList.add(new ExcelProperty("币种", dataList.size()));
				dataList.add(new ExcelProperty("毛利润", dataList.size()));
				dataList.add(new ExcelProperty("奖励", dataList.size()));
				dataList.add(new ExcelProperty("奖励日期", dataList.size()));
				reList.add(dataList);
				for (WorkFee workFee : workFees) {
					Work work = workFee.getWork();
					work.getItem().setName(!language.equals("zh_CH") ? work.getItem().getName_en() : work.getItem().getName_zh());
					dataList = new ArrayList<ExcelProperty>();
					dataList.add(new ExcelProperty(TimeUtil.getYYYY_MM(work.getDelegateTime()), dataList.size()));
					dataList.add(new ExcelProperty(work.getClient1().getNickname(), dataList.size()));
					dataList.add(new ExcelProperty(work.getWorkCode(), dataList.size()));
					dataList.add(new ExcelProperty(work.getItem().getName(), dataList.size()));
					if(work.getItem().getType() == 1){
						dataList.add(new ExcelProperty(work.getBoxAmount(), dataList.size()));
					}else if(work.getItem().getType() == 4){
						dataList.add(new ExcelProperty(work.getExpressWeight()+"KGS/"+work.getExpressVolume()+"CBM", dataList.size()));
					}else{
						dataList.add(new ExcelProperty(work.getGrossWeight()+"KGS/"+work.getVolume()+"CBM", dataList.size()));
					}
					dataList.add(new ExcelProperty(currency.getType(), dataList.size()));
					dataList.add(new ExcelProperty(work.getOption5(), dataList.size(), ExcelProperty.CONTENT_NUMBERIC));
					dataList.add(new ExcelProperty(work.getOption4(), dataList.size(), ExcelProperty.CONTENT_NUMBERIC));
					dataList.add(new ExcelProperty(workFee.getRewardTime() != null ? TimeUtil.getYYYY_MM_DD(workFee.getRewardTime()) : "", dataList.size()));
					reList.add(dataList);
				}
			}else if(statisticalType == 2){
				dataList = new ArrayList<ExcelProperty>();
				dataList.add(new ExcelProperty("订单委托月份", dataList.size()));
				dataList.add(new ExcelProperty("委托方", dataList.size()));
				dataList.add(new ExcelProperty("订单号", dataList.size()));
				dataList.add(new ExcelProperty("委托项目", dataList.size()));
				dataList.add(new ExcelProperty("货量", dataList.size()));
				dataList.add(new ExcelProperty("币种", dataList.size()));
				dataList.add(new ExcelProperty("毛利润", dataList.size()));
				dataList.add(new ExcelProperty("公司利润", dataList.size()));
				dataList.add(new ExcelProperty("奖励", dataList.size()));
				reList.add(dataList);
				for (Work work : list) {
					work.getItem().setName(!language.equals("zh_CH") ? work.getItem().getName_en() : work.getItem().getName_zh());
					dataList = new ArrayList<ExcelProperty>();
					dataList.add(new ExcelProperty(TimeUtil.getYYYY_MM(work.getDelegateTime()), dataList.size()));
					dataList.add(new ExcelProperty(work.getClient1().getNickname(), dataList.size()));
					dataList.add(new ExcelProperty(work.getWorkCode(), dataList.size()));
					dataList.add(new ExcelProperty(work.getItem().getName(), dataList.size()));
					if(work.getItem().getType() == 1){
						dataList.add(new ExcelProperty(work.getBoxAmount() == null ? "" : work.getBoxAmount(), dataList.size()));
					}else if(work.getItem().getType() == 4){
						work.setExpressWeight(work.getExpressWeight() == null ? 0f : work.getExpressWeight());
						work.setExpressVolume(work.getExpressVolume() == null ? 0f : work.getExpressVolume());
						dataList.add(new ExcelProperty(work.getExpressWeight()+"KGS/"+work.getExpressVolume()+"CBM", dataList.size()));
					}else{
						work.setGrossWeight(work.getGrossWeight() == null ? 0f : work.getGrossWeight());
						work.setVolume(work.getVolume() == null ? 0f : work.getVolume());
						dataList.add(new ExcelProperty(work.getGrossWeight()+"KGS/"+work.getVolume()+"CBM", dataList.size()));
					}
					dataList.add(new ExcelProperty(currency.getType(), dataList.size()));
					dataList.add(new ExcelProperty(work.getOption5(), dataList.size(), ExcelProperty.CONTENT_NUMBERIC));
					dataList.add(new ExcelProperty(work.getOption6(), dataList.size(), ExcelProperty.CONTENT_NUMBERIC));
					dataList.add(new ExcelProperty(work.getOption4(), dataList.size(), ExcelProperty.CONTENT_NUMBERIC));
					reList.add(dataList);
				}
			}else if(statisticalType == 3){
				dataList = new ArrayList<ExcelProperty>();
				dataList.add(new ExcelProperty("委托方", dataList.size()));
				dataList.add(new ExcelProperty("委托月份", dataList.size()));
				dataList.add(new ExcelProperty("委托项目", dataList.size()));
				dataList.add(new ExcelProperty("订单号", dataList.size()));
				dataList.add(new ExcelProperty("货量", dataList.size()));
				dataList.add(new ExcelProperty("出发地", dataList.size()));
				dataList.add(new ExcelProperty("目的地", dataList.size()));
				dataList.add(new ExcelProperty("订单状态", dataList.size()));
				reList.add(dataList);
				for (Work work : list) {
					if(work.getItem() == null){
						continue;
					}
					work.getItem().setName(!language.equals("zh_CH") ? work.getItem().getName_en() : work.getItem().getName_zh());
					dataList = new ArrayList<ExcelProperty>();
					dataList.add(new ExcelProperty(work.getClient1().getNickname(), dataList.size()));
					dataList.add(new ExcelProperty(TimeUtil.getYYYY_MM(work.getDelegateTime()), dataList.size()));
					dataList.add(new ExcelProperty(work.getItem().getName(), dataList.size()));
					dataList.add(new ExcelProperty(work.getWorkCode(), dataList.size()));
					if(work.getItem().getType() == 1){
						dataList.add(new ExcelProperty(work.getBoxAmount() == null ? "" : work.getBoxAmount(), dataList.size()));
					}else if(work.getItem().getType() == 4){
						work.setExpressWeight(work.getExpressWeight() == null ? 0f : work.getExpressWeight());
						work.setExpressVolume(work.getExpressVolume() == null ? 0f : work.getExpressVolume());
						dataList.add(new ExcelProperty(work.getExpressWeight()+"KGS/"+work.getExpressVolume()+"CBM", dataList.size()));
					}else{
						work.setGrossWeight(work.getGrossWeight() == null ? 0f : work.getGrossWeight());
						work.setVolume(work.getVolume() == null ? 0f : work.getVolume());
						dataList.add(new ExcelProperty(work.getGrossWeight()+"KGS/"+work.getVolume()+"CBM", dataList.size()));
					}
					dataList.add(new ExcelProperty(work.getPointORG() != null ? work.getPointORG().getFullname() : "", dataList.size()));
					dataList.add(new ExcelProperty(work.getPointDES() != null ? work.getPointDES().getFullname() : "", dataList.size()));
					String statusStr = null;
					if(work.getWorkingStatus() == 1){
						statusStr = "计划";
					}else if(work.getWorkingStatus() == 2){
						statusStr = "进行中";
					}else if(work.getWorkingStatus() == 3){
						statusStr = "已完成";
					}else if(work.getWorkingStatus() == 4){
						statusStr = "暂停";
					}else if(work.getWorkingStatus() == 5){
						statusStr = "已归档";
					}else if(work.getWorkingStatus() == 6){
						statusStr = "删除";
					}
					dataList.add(new ExcelProperty(statusStr, dataList.size()));
					reList.add(dataList);
				}
			}

			if(statisticalType == 1){
				title = "账务统计（个人奖励）";
			}else if(statisticalType == 2){
				title = "账务统计（公司利润）";
			}else if(statisticalType == 2){
				title = "账务统计（订单统计）";
			}
			String fileName = title + TimeUtil.getYYYY_MM_DD(new Date());
			excel.init(null, fileName, tiList, heList, reList, dataList.size());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 组装统计查询条件
	 * @return
	 */
	private Map<String, Object> getConditions() {
		HttpServletRequest request=ServletActionContext.getRequest();
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("status1", request.getParameter("status1"));
		conditions.put("status2", request.getParameter("status2"));
		conditions.put("status3", request.getParameter("status3"));
		conditions.put("status4", request.getParameter("status4"));
		String itemType = request.getParameter("itemTypeId");
		String clientId = request.getParameter("clientId");
		String minMonth = request.getParameter("minMonth");
		String maxMonth = request.getParameter("maxMonth");
		String tag = request.getParameter("tag");
		String rewardId = request.getParameter("rewardId");
		String delegateTime = request.getParameter("delegateTime");
		String teamId = request.getParameter("teamId");
		if(CommUtils.isCorrectInt(clientId)){
			conditions.put("employeeId", clientId);
		}
		if(minMonth != null && minMonth.length() > 0){
			conditions.put("minMonth", minMonth);
		}
		if(maxMonth != null && maxMonth.length() > 0){
			conditions.put("maxMonth", maxMonth);
		}
		if(tag != null && tag.length() > 0){
			conditions.put("tag", tag);
		}
		if(CommUtils.isCorrectInt(rewardId)){
			conditions.put("rewardId", rewardId);
		}
		if(CommUtils.isCorrectInt(itemType)){
			conditions.put("itemType", itemType); 
		}
		if(delegateTime != null && delegateTime.length() > 0){
			conditions.put("month", delegateTime);
		}
		if(CommUtils.isCorrectInt(teamId)){
			conditions.put("teamId", teamId); 
		}
		return conditions;
	}
	
	@Action("toStatisticsFinancial")
	public String toStatisticsFinancial(){
		HttpServletRequest request=ServletActionContext.getRequest();
		Employee employee = ActionUtil.getSelectEmployee();
		Company company = employee.getCompany();
		
		request.setAttribute("company", company);
		request.setAttribute("employee", employee);
		
		String statisticsType = request.getParameter("statisticsType");
		request.setAttribute("statisticsType", statisticsType);
		return "work/statisticsfinancial"; 
	}
	
	/**
	 * statisticsType=0应收未收, statisticsType=1应付未付
	 * statisticsFlag=0筛选, statisticsFlag=1详情
	 */
	@Action("statisticsFinancial")
	public String statisticsFinancial(){
		HttpServletRequest request=ServletActionContext.getRequest();
		try{
			String statisticsType = request.getParameter("statisticsType");
			if(("0".equals(statisticsType) || "1".equals(statisticsType))){
				String language = CookieUtil.getCookieValue(request, "cts_locale");
				String companyId = request.getParameter("companyId");
				Company company = null;
				if(CommUtils.isCorrectInt(companyId)){
					company = commonManager.findEntityByPK(Company.class, Long.parseLong(companyId));
				}
				List<WorkFee> workFees = this.workManager.statisticsFinancial(company, Integer.parseInt(statisticsType), request.getParameter("clientId"), request.getParameter("months"), 
					request.getParameter("days"), request.getParameter("employeeId"), request.getParameter("tag"), request.getParameter("status1"), pageSize, pageNumber);
				if(workFees != null && workFees.size() >0){
					Map<Employee, Map<Currency, Float>> map = new LinkedHashMap<Employee, Map<Currency,Float>>();
					Map<Currency, Float> totalMap = new LinkedHashMap<Currency, Float>();
					for(WorkFee fee: workFees){
						if(map.containsKey(fee.getEmployee1())){
							Map<Currency, Float> currency = map.get(fee.getEmployee1());
							if(currency.containsKey(fee.getCurrency())){
								float moneysum = currency.get(fee.getCurrency());
								moneysum += safeFloat(fee.getMoney()) - safeFloat(fee.getWrittenOffmoney());
								currency.put(fee.getCurrency(), moneysum);
							}else{
								currency.put(fee.getCurrency(), safeFloat(fee.getMoney()) - safeFloat(fee.getWrittenOffmoney()));
							}
							
							if(totalMap.containsKey(fee.getCurrency())){
								float totalsum = totalMap.get(fee.getCurrency());
								totalsum += safeFloat(fee.getMoney()) - safeFloat(fee.getWrittenOffmoney());
								totalMap.put(fee.getCurrency(), totalsum);
							}else{
								totalMap.put(fee.getCurrency(), safeFloat(fee.getMoney()) - safeFloat(fee.getWrittenOffmoney()));
							}
						}else{
							Map<Currency, Float> currency = new LinkedHashMap<Currency, Float>();
							currency.put(fee.getCurrency(), safeFloat(fee.getMoney()) - safeFloat(fee.getWrittenOffmoney()));
							map.put(fee.getEmployee1(), currency);
							
							totalMap.put(fee.getCurrency(), safeFloat(fee.getMoney()) - safeFloat(fee.getWrittenOffmoney()));
						}
					}
					request.setAttribute("map", map);
					request.setAttribute("totalMap", totalMap);
				}
			}
			request.setAttribute("statisticsType", statisticsType);
		}catch(Exception e){
			e.printStackTrace();
		}
		return "work/statisticsfinancialdata";
	}
	
	@Action("statisticsFinancialItems")
	public String statisticsFinancialItems(){
		HttpServletRequest request=ServletActionContext.getRequest();
		try{
			String statisticsType = request.getParameter("statisticsType");
			if(("0".equals(statisticsType) || "1".equals(statisticsType))){
				String language = CookieUtil.getCookieValue(request, "cts_locale");
				String companyId = request.getParameter("companyId");
				Company company = null;
				if(CommUtils.isCorrectInt(companyId)){
					company = commonManager.findEntityByPK(Company.class, Long.parseLong(companyId));
				}
				List<WorkFee> workFees = this.workManager.statisticsFinancial(company, Integer.parseInt(statisticsType), request.getParameter("clientId"), request.getParameter("months"), 
					request.getParameter("days"), request.getParameter("employeeId"), request.getParameter("tag"), request.getParameter("status1"), pageSize, pageNumber);
				for(WorkFee workFee: workFees){
					Work work = workFee.getWork();
					work.setOption2(TimeUtil.daysOfTwo(work.getDelegateTime(), new Date()) + "");
					
					Fee fee = workFee.getFee();
					fee.setName(!language.equals("zh_CH") ? fee.getName_en() : fee.getName_zh());
				}
				request.setAttribute("workFees", workFees);
			}
			request.setAttribute("statisticsType", statisticsType);
		}catch(Exception e){
			e.printStackTrace();
		}
		return "work/statisticsfinancialdatadetail";
	}
	
	@Action("exportStatisticsFinancial")
	public String exportStatisticsFinancial(){
		HttpServletRequest request=ServletActionContext.getRequest();
		try{
			String statisticsType = request.getParameter("statisticsType");
			if(("0".equals(statisticsType) || "1".equals(statisticsType))){
				String language = CookieUtil.getCookieValue(request, "cts_locale");
				String companyId = request.getParameter("companyId");
				Company company = null;
				if(CommUtils.isCorrectInt(companyId)){
					company = commonManager.findEntityByPK(Company.class, Long.parseLong(companyId));
				}
				List<WorkFee> workFees = this.workManager.statisticsFinancial(company, Integer.parseInt(statisticsType), request.getParameter("clientId"), request.getParameter("months"), 
					request.getParameter("days"), request.getParameter("employeeId"), request.getParameter("tag"), request.getParameter("status1"), pageSize, pageNumber);
				
				ExportExcel excel = new ExportExcel();
				List<List<ExcelProperty>> reList = new ArrayList<List<ExcelProperty>>();
				List<List<ExcelTitle>> tiList = new ArrayList<List<ExcelTitle>>();
				List<List<ExcelTitle>> heList = new ArrayList<List<ExcelTitle>>();
				int i = 0;
				List<ExcelProperty> dataList = null;
				
				if(workFees != null && workFees.size() > 0){
					i = 0;
					dataList = new ArrayList<ExcelProperty>();
					
					dataList.add(new ExcelProperty("结算方", i++));
					dataList.add(new ExcelProperty("订单号", i++));
					dataList.add(new ExcelProperty("费用名称", i++));
					dataList.add(new ExcelProperty("币种", i++));
					dataList.add(new ExcelProperty("0".equals(statisticsType) ? "应收款" : "应付款", i++));
					dataList.add(new ExcelProperty("未结算金额", i++));
					dataList.add(new ExcelProperty("委托至今", i++));
					dataList.add(new ExcelProperty("订单创建者", i++));
					
					reList.add(dataList);
					for(WorkFee workFee: workFees){
						i = 0;
						dataList = new ArrayList<ExcelProperty>();

						dataList.add(new ExcelProperty(workFee.getEmployee1().getNickname(), i++));
						dataList.add(new ExcelProperty(workFee.getWork().getWorkCode(), i++));
						dataList.add(new ExcelProperty(!language.equals("zh_CH") ? workFee.getFee().getName_en() : workFee.getFee().getName_zh(), i++));
						dataList.add(new ExcelProperty(workFee.getCurrency().getType(), i++));
						dataList.add(new ExcelProperty(workFee.getMoney() + "", i++, ExcelProperty.CONTENT_NUMBERIC));
						dataList.add(new ExcelProperty(workFee.getNotWrittenOffmoney() + "", i++, ExcelProperty.CONTENT_NUMBERIC));
						dataList.add(new ExcelProperty(TimeUtil.daysOfTwo(workFee.getWork().getDelegateTime(), new Date()) + "天", i++));
						dataList.add(new ExcelProperty(workFee.getWork().getEmployee().getNickname(), i++));

						reList.add(dataList);
					}
					
					String title = null;
					if("0".equals(statisticsType)){
						title = "统计应收未收";
					}else{
						title = "统计应付未付";
					}
					String fileName = title + TimeUtil.getYYYY_MM_DD(new Date());
					excel.init(null, fileName, tiList, heList, reList, dataList.size());
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	//根据订单号码查询货物（首页货物追踪）
	@Action("searchByOrder")
	public String searchByOrder(){
		HttpServletRequest request=ServletActionContext.getRequest();
		List<WorkItem> workItem1=new ArrayList<WorkItem>();
		List<WorkItem> workItem2=new ArrayList<WorkItem>();
		List<WorkItem> workItem3=new ArrayList<WorkItem>();
		List<WorkItem> workItem4=new ArrayList<WorkItem>();
		List<WorkItem> workItem5=new ArrayList<WorkItem>();
		List<WorkItem> workItem6=new ArrayList<WorkItem>();
		
		List<Work> workList=this.commonManager.findByCustomizedSQL(Work.class, " workCode='"+keyword+"'");
		if(workList!=null && workList.size()>0){
			work=workList.get(0);
//			主航线的ORG到POL的天数
			if(work.getDepartureTime2()!=null && work.getDepartureTime1()!=null){
				int day1=TimeUtil.daysOfTwo(work.getDepartureTime1(),work.getDepartureTime2());
				if(day1==0)day1=1;
				request.setAttribute("day1", day1);
			}
			//主航线的POD到DES的天数
			if(work.getArrivalTime2()!=null && work.getArrivalTime1()!=null){
				int day2=TimeUtil.daysOfTwo(work.getArrivalTime1(),work.getArrivalTime2());
				if(day2==0)day2=1;
				request.setAttribute("day2", day2);
			}
			
			//费用
			List<WorkFee> fees1 = this.workManager.getFeesByWork( work, 0 );// 应收款
			List<WorkFee> fees2 = this.workManager.getFeesByWork( work, 1 );// 应付款
			work.setOption11(fees1);
			work.setOption12(fees2);
			
			List<WorkItem> items = this.workManager.getItemsByWork( work );//其他委托项目
			if( items!=null && items.size()>0 ){
				for( WorkItem obj2: items ){
					int day=TimeUtil.daysOfTwo(obj2.getStartTime(), obj2.getEndTime());
					if(day==0)day=1;
					obj2.setOption2(day+"");//设置每个委托项目的天数
					
					if(TimeUtil.toDayIsBetweenDates(obj2.getStartTime(), obj2.getEndTime())){
						obj2.setOption1(2);//任何进行中
					}else if( TimeUtil.dateTimeIsPass(obj2.getEndTime())>=0){
						obj2.setOption1(1);//任务已经完成
					}else{
						obj2.setOption1(0);
					}
					//如果是出发地ORG
					if(obj2.getType()==1){
						workItem2.add(obj2);
					}else if(obj2.getType()==2){ //如果是出发港POL
						workItem3.add(obj2);
					}else if(obj2.getType()==3){ //如果是到达港POD
						workItem4.add(obj2);
					}else if(obj2.getType()==4){ //如果是目的地DES
						workItem5.add(obj2);
					}
				}
				work.setOption13(items);
			}
		
			request.setAttribute("workItem1", workItem1);//出发地ORG的委托项目短途运输类型list
			request.setAttribute("workItem2", workItem2);//出发地ORG的委托项目非短途运输类型list
			request.setAttribute("workItem3", workItem3);//出发港POL的委托项目list
			request.setAttribute("workItem4", workItem4);//到达港POD的委托项目list
			request.setAttribute("workItem5", workItem5);//目的地DES的委托项目非短途运输类型list
			request.setAttribute("workItem6", workItem6);//目的地DES的委托项目短途运输类型list
			
//			算出发时间到到达时间的百分比
			Date beginDate=null;
			Date nowDate=new Date();
			Date endDate=null;
			if((work.getPointORG()!=null || work.getPointPOL()!=null) && (work.getPointPOD()!=null || work.getPointDES()!=null)){
				if(work.getItem().getType()<4){
					if(work.getPointORG().getId()==work.getPointPOL().getId()){
						beginDate=work.getDepartureTime2();
					}else{
						beginDate=work.getDepartureTime1();
					}
					if(work.getPointPOD().getId()==work.getPointDES().getId()){
						endDate=work.getArrivalTime1();
						if(endDate==null){
							endDate=work.getEta1();
						}
					}else{
						endDate=work.getArrivalTime2();
						if(endDate==null){
							endDate=work.getEtd2();
						}
					}
				}else if(work.getItem().getType()==4){
					beginDate=work.getExpressGetTime();
					endDate=work.getExpressPutTime();
					if(endDate==null){
						endDate=work.getExpressETA();
					}
				}else if(work.getItem().getType()==5){
					beginDate=work.getTruckingTime1();
					endDate=work.getTruckingTime2();
					if(endDate==null){
						endDate=work.getTruckingETA();
					}
				}
				if(beginDate!=null && endDate!=null){
					int m1=TimeUtil.minutesOfTwo(beginDate, endDate);
					int m2=TimeUtil.minutesOfTwo(beginDate, nowDate);
					
					double mPercent=(double)m2/m1;
					if(mPercent<0){
						mPercent=0;
					}else if(mPercent>1){
						mPercent=1;
					}
					BigDecimal b=new BigDecimal(mPercent);
					mPercent=b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
					request.setAttribute("percent", mPercent);//计算用的百分比（如0.85）
				}
			}
			//主航线的天数
			if(beginDate!=null && endDate!=null){
				int totalDay=TimeUtil.daysOfTwo(beginDate,endDate);
				request.setAttribute("totalDay", totalDay+1);
			}
		}else{
			request.setAttribute("isExist", "no");
		}
		
		return "work/working";
	}
	
	private float safeFloat(Float f){
		if(f == null){
			return 0f;
		}
		return f;
	}
	
	public void setWorkManager(IWorkManager workManager) {
		this.workManager = workManager;
	}

	public Integer getItemType() {
		return itemType;
	}

	public void setItemType(Integer itemType) {
		this.itemType = itemType;
	}

	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	public String getKeyword() {
		return keyword;
	}
	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
	public void setCommonManager(CommonManager commonManager) {
		this.commonManager = commonManager;
	}
	public CommonManager getCommonManager() {
		return commonManager;
	}
	public IWorkManager getWorkManager() {
		return workManager;
	}
	public Work getWork() {
		return work;
	}
	public void setWork(Work work) {
		this.work = work;
	}

	public IExcRateManager getExcRateManager(){
		return excRateManager;
	}

	public void setExcRateManager(IExcRateManager excRateManager){
		this.excRateManager = excRateManager;
	}
	
	public ContainerNo getContainerNo() {
		return containerNo;
	}

	public void setContainerNo(ContainerNo containerNo) {
		this.containerNo = containerNo;
	}

	public String getContentType(){
		return contentType;
	}

	public void setContentType(String contentType){
		this.contentType = contentType;
	}

	public String getFileName(){
		return fileName;
	}

	public void setFileName(String fileName){
		this.fileName = fileName;
	}

	public File getMyFile(){
		return myFile;
	}

	public void setMyFile(File myFile){
		this.myFile = myFile;
	}

	public String getMyFileContentType(){
		return myFileContentType;
	}

	public void setMyFileContentType(String myFileContentType){
		this.myFileContentType = myFileContentType;
	}

	public String getMyFileFileName(){
		return myFileFileName;
	}

	public void setMyFileFileName(String myFileFileName){
		this.myFileFileName = myFileFileName;
	}

	public WorkItem getWorkItem() {
		return workItem;
	}

	public void setWorkItem(WorkItem workItem) {
		this.workItem = workItem;
	}

	public List<String> getTagsList() {
		return tagsList;
	}

	public void setTagsList(List<String> tagsList) {
		this.tagsList = tagsList;
	}
}
